Shall list members be injected into domain model? - dependency-injection

Lately, I have invested my efforts into learning and understanding DI. Now that I'm growing more fluent with it, some other concerns come up.
Shall list members be injected into domain model?
In the famous example of Ninject, the idea as I see it is:
public class Warrior {
public Warrior(IWeapon weapon) { this.weapon = weapon; }
public void Attack() { weapon.Hit(); }
}
public Archer : Warrior {
// Here, the weapon would be bound to a bow.
public Archer(IWeapon weapon) : base(weapon) { }
}
public Ninja : Warrior {
// On the contrary, the weapon would here be bound to a katana.
public Ninja(IWeapon weapon) : base(weapon) { }
}
Hence contextual binding to define what weapon should be created depending on what the IWeapon is injected into.
I understand that injecting a DAO into my model would be implementing the Active Record design pattern, which is considered somehow an anti-pattern by some people. Others would prefer POCOs as domain objects, simple data representation, which is not following the rules of DDD.
Back to my concern, I would say that Warrior, Archer and Ninja are all part of my domain model.
Now, what if my model has an IList<T> instead of a IWeapon? Would DI be of any use, or would it become useless?
public class MyClass {
public MyClass(IList<MyOtherClass> myOtherClasses) {
MyOtherClassesA = myOtherClasses.OfType<MyOtherClassA>().ToList();
MyOtherClassesB = myOtherClasses.OfType<MyOtherClassB>().ToList();
}
public IList<MyOtherClassA> MyOtherClassesA { get; protected set; }
public IList<MyOtherClassB> MyOtherClassesB { get; protected set; }
}
Am I pushing it too far?
Am I missing something?
EDIT
No, do inject them! But don't inject one list of a base type, which you then split by derived types.
Let's put ourselves in the context of Scrum and a Sprint.
In a Sprint, the Development Team may have Bugs, Impediments, Tasks and UserStories.
All of these have a Title and a Description, plus some other properties specific to each type. Let's make an abstract class called Artifact (not ScrumArtifact).
Artifact
public abstract class Artifact {
public string Description { get; set; }
public string Title { get; set; }
}
Bug
public class Bug : Artifact {
public string Resolution { get; set; }
}
Impediment
public class Impediment : Artifact {
}
Task
public class Task : Artifact {
public float EstimatedTime { get; set; }
public float RealTime { get; set; }
}
UserStory
public class UserStory : Artifact {
public string AcceptanceCriteria { get; set; }
public int BusinessValue { get; set; }
public int Complexity { get; set; }
public IList<Impediment> Impediments { get; protected set; }
public IList<Task> Tasks { get; protected set; }
}
Here, I have a UserStory which "depends" on two lists: Impediments and Tasks.
So I should have the constructor of UserStory taking two lists as follows.
public UserStory(IList<Impediment> impediments, IList<Task> tasks) {
Impediments = impediments;
Tasks = tasks;
}
And my unit test:
[TestFixture]
public class UserStoryTests {
[Test]
public void ImpedimentsShouldBeInitializedByDefault() {
userStory.Impediments.Should().NotBeNull().And.BeOfType<IList<Impediment>>();
}
public void TasksShouldBeInitializedByDefault() {
userStory.Tasks.Should().NotBeNull().And.BeOfType<IList<Task>>();
}
[TestFixtureSetUp]
public void UserStorySetUp() {
impediments = new Mock<IList<Impediment>>();
tasks = new Mock<IList<Task>>();
userStory = new UserStory(impediments.Object, tasks.Object);
}
private Mock<IList<Impediment>> impediments;
private Mock<IList<Task>> tasks;
private UserStory userStory;
}
The problem comes with the Sprint. The Sprint rather require four lists, and I find it too much of objects to inject for clarity and readability. It is said, if I'm not mistaken, that a class with too much dependencies might break the Single Responsibility Principle. Though I'm not breaking the SRP even with the Sprint class, I feel quite uncomfortable with injecting four different lists. I thought I could use polymorphism to inject one list which would contain them all, since after all they are all basically Artifacts.
Perhaps shall I simply consider using the AbstractFactory pattern so that my four lists get initialized properly as expected, and I would only have to inject one single factory class which single responsibility consist of creating lists?

I think you misinterpreted the Ninject example a little bit. It doesn't involve different warrior classes, which are tied to a specific subtype of IWeapon. There's only a Samurai, who can use any type of IWeapon. So an Archer, who can only use a specific kind of weapon is not accounted for and wouldn't fit in well. Instead just inject a Bow into a Samurai.
Injecting lists is totally OK. Some DI containers even allow for autowiring lists. I.e. you can tell the container to inject all implementations of your interface found in a given assembly as a list.
But that only really works if you can treat all members in the same way, i.e. you don't have to differentiate by subtype. If you want to separate your warrior's melee weapons from his collection of bows, it's better to inject two different lists of two different types.
If you want to learn more about proper DI patterns, I can very much recommend Dependency Injection in .NET by Mark Seemann.

Related

Multiple database contexts when using repository pattern

I am a bit lost right now... I've never seen this much divergent information regarding solution to the problem. But let us start from the beginning.
I am using ASP.NET MVC with Repositories injected to Controllers, thanks to the Ninject. I have 2 simple Entities: Admin with a list of created blog entries and Entries with one virtual Admin field.
Admin:
public class Admin
{
[Key, ScaffoldColumn(false)]
public int Id { get; set; }
[Required(ErrorMessage = "Zły login.")]
[StringLength(20), MinLength(3)]
[RegularExpression(#"^[a-zA-Z0-9]*$", ErrorMessage = "Special characters are not allowed.")]
public string Login { get; set; }
[Required(ErrorMessage = "Złe hasło.")]
[StringLength(20, MinimumLength = 3)]
[DataType(DataType.Password)]
[Display(Name = "Hasło")]
public string Password { get; set; }
public virtual List<Entry> CreatedEntries { get; set; } // napisane aktualności przez danego admina
}
Entry:
public class Entry
{
[Key, ScaffoldColumn(false)]
public int Id { get; set; }
[StringLength(200, MinimumLength = 2)]
[DataType(DataType.Text)]
[Display(Name = "Tytuł")]
public string Title { get; set; }
[Required, StringLength(2000), MinLength(3)]
[Display(Name = "Treść")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string Text { get; set; }
public virtual Admin Admin { get; set; }
}
You probably know where it is going, since this problem is... "classic" on stackoverflow.
In the Controller I want to bind one object to another:
entry.Admin = repAdmins.GetAdmin(User.Identity.Name);
repEntries.AddEntry(entry);
In the repository:
public void AddEntry(Entry entry)
{
db.Entries.Add(entry);
db.SaveChanges();
}
Of course I can't do that, because of famous "An entity object cannot be referenced by multiple instances of IEntityChangeTracker", which is a result of having separate database contexts in each repository.
When I was searching for a solution I already knew that probably the best way to solve it is to use one common context. And then I discovered Unit Of Work pattern. But here's when the real problems starts.
On many sites the solution to this is a bit different.
The repositories must have common generic interface (which I don't want to use, because I don't need to have each CRUD operation on each Entity, plus sometimes I need to have extra methods like "IfExists", etc.)
On few sites I've read that this whole abstraction is not needed, since abstraction is already provided with Entity Framework and UoW is implemented in DbContext (whatever that means)
The Unit Of Work pattern (at least from examples on the internet) seems to be a real pain for me...
I need some guidance... I learn ASP.NET MVC for only a year. For me it seems like it's a "triumph of form over content". Because... What I simply need is to bind one object to another. I'm starting to think that it was better when I simply had a context object in the Controller and I didn't need to build Eiffel Tower to achieve what's mentioned above :\ However I like idea of repositories...
I'll open by simply answering the question straight-out. Simply, your repository should take the context as a dependency (it should have a constructor that accepts a param of type DbContext). Your context should be managed by Ninject, and then injected into your repository and/or your controller. That way, everything always uses the same context. You should do all this in "request" scope, so that the context is specific to the current request.
That said, I'd like to hit some of your other points. First, a repository is just a method of access. It really shouldn't be dependent on the entity. It's okay to have methods that you don't intend to use on a particular entity: just don't use them. However, if you do want to enforce this, you can always use generic constraints and interfaces. For example, let's say you don't want update available on a particular entity. You could have interfaces like:
public interface ICreateable
{
}
public interface IUpdateable : ICreateable
{
}
Then, your entity that should not be updated will implement only ICreateable while other entities (which allow update) would implement IUpdateable (which by interface inheritance, also implement ICreateable). Finally, you would add constraints on your repository methods:
public void Create<TEntity>(TEntity entity)
where TEntity : class, ICreateable
public void Update<TEntity>(TEntity entity>)
where TEntity : class, IUpdateable
Since, the entity in question only implements ICreatable, it will not be eligible to be used as a type param to Update, so there's then no way to utilize that method.
Next, the advice to not use the repository/UoW patterns with Entity Framework is indeed because Entity Framework already implements these patterns. The repository pattern exists as a way to contain all the database querying logic (constructing SQL statements and such) in one place. That is the "abstraction" we're talking about here. In other words, instead of directly constructing SQL statements in your application code, that code is abstracted away into a repository. However, this is exactly what Entity Framework does, which is why you don't need to do it again. The Unit of Work pattern exists as a method to orchestrate the work of multiple repositories, allowing things like transactions. However, again, Entity Framework does all this.
The only reason to add any further abstraction is if you want to abstract the actual provider, i.e. Entity Framework itself. For example, you could have an interface like IRepository and then create implementations like EntityFrameworkRepository, NHibernateRepository, WebApiRepository, etc. Your application would only ever depend on IRepository, and you could then sub in different implementations as needed. If you're not going to do this, or you will always be using Entity Framework, then you might as well just use your context directly. Any further abstraction is just something else to maintain with no benefit at all to your application.
Finally, yes, the Unit of Work pattern is a real pain to everyone, not just you. Which is why I forgo it entirely. I use what I call a "truly generic repository", which utilizes generic methods and interfaces to handle any entity I want to throw at it. That means it acts not only as a repository but also a unit of work as well. You only need one instance per context and it's provider-agnostic. For more information check out the article I wrote on the subject over on my website.
The following example shows how to use the same context within multiple repositories. To simplify it, I did not use interfaces and nor did I use a container to inject dependencies.
Controller class:
public class HomeController : Controller
{
Context context;
AdminRepository adminRepository;
EntryRepository entryRepository;
public HomeController()
{
context = new Context();
adminRepository = new AdminRepository(context);
entryRepository = new EntryRepository(context);
}
// GET: Home
public ActionResult Index()
{
string login = "MyLogin";
Admin admin = adminRepository.GetAdmin(login);
Entry entry = new Entry() { Admin = admin};
entryRepository.AddEntry(entry);
return View(entry);
}
}
Repositories:
public class AdminRepository
{
Context context;
public AdminRepository(Context context)
{
this.context = context;
// This seeds the database
Admin admin = new Admin() { Login = "MyLogin" };
this.context.Admins.Add(admin);
this.context.SaveChanges();
}
public Admin GetAdmin(string login)
{
return context.Admins.Where(a => a.Login == login).FirstOrDefault();
}
}
public class EntryRepository
{
Context context;
public EntryRepository(Context context)
{
this.context = context;
}
public void AddEntry(Entry entry){
context.Entrys.Add(entry);
context.SaveChanges();
}
}
Context class:
public class Context : DbContext
{
public Context()
{
Database.SetInitializer<Context>(new DropCreateDatabaseAlways<Context>());
Database.Initialize(true);
}
public DbSet<Admin> Admins { get; set; }
public DbSet<Entry> Entrys { get; set; }
}
Modified Models:
public class Admin
{
public int Id { get; set; }
public string Login { get; set; }
}
public class Entry
{
public int Id { get; set; }
public virtual Admin Admin { get; set; }
}

Using DTO to transfer data between service layer and UI layer

I've been trying to figure this out for days but there seems to be very little info on this particular subject with ASP.NET MVC. I've been Googling around for days and haven't really been able to figure anything out about this particular issue.
I've got a 3 layer project. Business, DAL and UI/Web layer. In the DAL is dbcontext, repository and unit of work. In the business layer is a domain layer with all the interfaces and the EF models. In the business layer there is also a service layer with DTOs for the EF models and a generic repository service that accesses the repository. This picture should help explain it.
My problem is that i just can't seem to figure out how to use the DTOs to transfer data from the business layer.
I've created service classes for the DTOs. I've got a ImageDTO and model and same for image anchors. I've created a service class for each DTO. So i've got a image service and anchor service. These services inherit the repository service and at the moment implement their own services. But thats about as far as i have gotten. Since these services have constructors that receive a IUnitOfWork interface via IoC i've pretty much gotten stranded.
If i reference the service directly from the UI everything works as it should but i just can't get my mind around how to use DTOs to transmit data both from the service layer to the UI layer and the other way around.
My service layer:
Business/Services/DTOs
public class AnchorDto
{
public int Id { get; set; }
public int x1 { get; set; }
public int y1 { get; set; }
public int x2 { get; set; }
public int y2 { get; set; }
public string description { get; set; }
public int imageId { get; set; }
public int targetImageId { get; set; }
public AnchorDto(int Id, int x1, int y1, int x2, int y2, string description, int imageId, int targetImageId)
{
// Just mapping input to the DTO
}
}
public class ImageDto
{
public int Id { get; set; }
public string name { get; set; }
public string title { get; set; }
public string description { get; set; }
public virtual IList<AnchorDto> anchors { get; set; }
public ImageDto(int Id, string name, string title, string description, IList<AnchorDto> anchors )
{
// Just mapping input to DTO
}
}
Business/Services/Services
public class RepoService<TEntity> : IRepoService<TEntity> where TEntity : class
{
private IRepository<TEntity> repo;
public RepoService(IUnitOfWork repo)
{
this.repo = repo.GetRepository<TEntity>();
}
public IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
return repo.Get(filter, orderBy, includeProperties);
}
public TEntity GetByID(object id)
{
return repo.GetByID(id);
}
public void Insert(TEntity entity)
{
repo.Insert(entity);
}
public void Delete(object id)
{
repo.Delete(id);
}
public void Delete(TEntity entityToDelete)
{
repo.Delete(entityToDelete);
}
public void Update(TEntity entityToUpdate)
{
repo.Update(entityToUpdate);
}
}
The Image Service, the IImageService interface is currently empty until i figure out what i need to implement.
public class ImageService : RepoService<ImageModel>, IImageService
{
public ImageService(IUnitOfWork repo)
: base(repo)
{
}
}
At the moment my controllers aren't really working and aren't using the service layer so i decided not to include any of those. I plan to map the DTOs to ViewModels using auto mapper once i've sorted this issue out.
So now, please anyone knowledgeable enough to give me that idea I'm missing so that i can figure this out?
Your service should receive DTOs, map them to business entities and send them to the repository. It should also retrieve business entities from the repository, map them to DTOs and return the DTOs as reponses. So your business entities never get out from the business layer, only the DTOs do.
Then your UI\Weblayer should be unaware of the business entities. The web layer should only know about the DTOs. To enforce this rule is very important that your UI layer does not uses the service implementation classes (which should be private), just the interfaces. And the service interfaces shouldn´t depend on the business entities, just the DTOs.
So you need service interfaces based on DTOs, and your base service class needs another generic argument for the DTO. I like to have a base class for entities and DTOs so they can be declared as:
//Your UI\presentation layer will work with the interfaces (The inheriting ones)
//so it is very important that there is no dependency
//on the business entities in the interface, just on the DTOs!
protected interface IRepoService<TDto>
where TDto: DTOBase
{
//I'm just adding a couple of methods but you get the idea
TDto GetByID(object id);
void Update(TDto entityToUpdateDto)
}
//This is the interface that will be used by your UI layer
public IImageService: IRepoService<ImageDTO>
{
}
//This class and the ones inheriting should never be used by your
//presentation\UI layer because they depend on the business entities!
//(And it is a best practice to depend on interfaces, anyway)
protected abstract class RepoService<TEntity, TDto> : IRepoService<TDto>
where TEntity : EntityBase
where TDto: DTOBase
{
...
}
//This class should never be used by your service layer.
//Your UI layer should always use IImageService
//You could have a different namespace like Service.Implementation and make sure
//it is not included by your UI layer
public class ImageService : RepoService<ImageModel, ImageDto>, IImageService
{
...
}
You then need a way of adding the mapping between entities and DTO to that base service without actually implementing the mapping (as it depends on each concrete entity and DTO classes). You could declare abstract methods that perform the mapping and will need to be implemented on each specific service (like ImageService). The implemantion of the base RepoService would look like:
public TDto GetByID(object id)
{
//I'm writing it this way so its clear what the method is doing
var entity = repo.GetByID(id);
var dto = this.EntityToDto(entity);
return dto;
}
public void Update(TDto entityToUpdateDto)
{
var entity = this.DtoToEntity(entityToUpdateDto)
repo.Update(entity);
}
//These methods will need to be implemented by every service like ImageService
protected abstract TEntity DtoToEntity(TDto dto);
protected abstract TDto EntityToDto(TEntity entity);
Or you could declare mapping services, adding a dependency with an appropiated mapping service that should be provided by your IOC (This makes more sense if you need the same mapping on different services). The implementation of RepoService would look like:
private IRepository<TEntity> _repo;
private IDtoMappingService<TEntity, TDto> _mappingService;
public RepoService(IUnitOfWork repo, IDtoMappingService<TEntity, TDto> mapping)
{
_repo = repo.GetRepository<TEntity>();
_mappingService = mapping;
}
public TDto GetByID(object id)
{
//I'm writing it this way so its clear what the method is doing
var entity = repo.GetByID(id);
var dto = _mappingService.EntityToDto(entity);
return dto;
}
public void Update(TDto entityToUpdateDto)
{
var entity = _mappingService.DtoToEntity(entityToUpdateDto)
repo.Update(entity);
}
//You will need to create implementations of this interface for each
//TEntity-TDto combination
//Then include them in your dependency injection configuration
public interface IDtoMappingService<TEntity, TDto>
where TEntity : EntityBase
where TDto: DTOBase
{
public TEntity DtoToEntity(TDto dto);
public TDto EntityToDto(TEntity entity);
}
In both cases (abstract methods or mapping services), you can implement the mapping between the entities and DTOs manually or using a tool like Automapper. But you should be very careful when using the AutoMapper and entity framework, although that is another topic! (Google a bit about that and collect some information on the topic. As a first advice pay attention to the queries being executed against the database when loading data so you don´t load more than needed or send many queries. When saving data pay attention to your collections and relationships)
Long post maybe, but I hope it helps!

Testing: Entity Framework by faking context

I am eating myself up at this moment. It is like Entity Framework isn't testable. I've read alot of posts and threads where they use unit of work or moq or the repo pattern.
I am in a phase that i can't change alot of my architechture of my application. The application fully works at this moment but to be sure I need to have a high code coverage, so testing it is.
For testing, I am using the 'fake context' method where I can use the fake one for mocking and the real one for connection to the database.
I used this as an example.
http://romiller.com/2010/09/07/ef-ctp4-tips-tricks-testing-with-fake-dbcontext/
There, you can see that the context is splitted and used as an interface. Like:
public interface IEmployeeContext
{
IDbSet Department Departments { get; }
IDbSet Employee Employees { get; }
int SaveChanges();
}
public class EmployeeContext : DbContext, IEmployeeContext
{
public IDbSet Department Departments { get; set; }
public IDbSet Employee Employees { get; set; }
}
public class FakeEmployeeContext : IEmployeeContext
{
public FakeEmployeeContext()
{
this.Departments = new FakeDepartmentSet();
this.Employees = new FakeEmployeeSet();
}
public IDbSet Department Departments { get; private set; }
public IDbSet Employee Employees { get; private set; }
public int SaveChanges()
{
return 0;
}
}
}
So tesing and everything works. The only thing i can't seem to do, is test a controller with .State in it where i check whether it's changed Like:
EntityState.Modified
Because this uses an interface I need to add that into the interface context. And create a new one. Or am I missing something ? It is likely not the intention that I create the whole method in that context.. How can I manage to get this to work
Have you considered performing integration tests instead?
You can have integration tests against a real EF DBContext,
just give it a different connection string in the App.config of the unit-tests project.
Read this and all of the answers to it.
Just add the property in the context interface. Btw, you don't need the FakeContext, you can just create a mock of the interface, and setup the properties to return your fake datasets. That way, you can add/remove as many methods and properties in the interface, as you need.
Thanks to #Liel I managed to get this work. creating a 'test' db for integration testing.. instead of using unnecesary code in my opinion. My project is now fully independend by using this method.
[TestInitialize]
public void InitializBeforeTests()
{
AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""));
Database.SetInitializer<DataAccess.DataContext>(new DropCreateDatabaseAlways<DataAccess.DataContext>());
var context = new DataAccess.DataContext();
context.Database.Initialize(force: true);
}
and creating a new connection string in my test project in APP.Config.
Thanks all for your answers !

Using a domain model incorporated with a State pattern

There's a task connected with changing state of an entity. And I'm quite confused thinking whether it should be an event-based approach which involves something like CQRS or I can use a State pattern and leave all logic inside the entities.
I have found an article which shows a domain model (or a piece of it) that uses a State pattern: http://www.prowareness.com/blog/?p=1448
Ordering system is quite close to my domain model. So the example is great. But still I'm wondering if it is a good practice considering MVC pattern and if it is possible to implement with RavenDB/NHibernate?
EDIT: question rethought
Let's follow the example:
First, here's a domain entity called Idea:
[Serializable]
public class Idea : AbstractEntity<Guid> {
private static IStateFactory stateFactory;
private AbstractState state = new InitiatedState();
[Required, StringLength(150)]
public String Title { get; set; }
[Required]
public String ProblemContext { get; set; }
public DateTime CreatedOn { get; set; }
public Guid InitiatorId { get; set; }
[Required]
public Decimal InvestmentAmount { get; set; }
public Boolean IsInitiated {
get { return this.state.IsInitiated; }
}
public Boolean IsRejected {
get { return this.state.IsRejected; }
}
public Boolean IsUnderInitialAssessment {
get { return this.state.IsUnderInitialAssessment; }
}
public Boolean IsConfirmedForImplementation {
get { return this.state.IsConfirmedForImplementation; }
}
}
Whereas AbstractState is:
public abstract class AbstractState {
public virtual Boolean IsInitiated {
get { return true; }
}
public virtual Boolean IsRejected {
get { return false; }
}
public virtual Boolean IsUnderInitialAssessment {
get { return false; }
}
public virtual Boolean IsConfirmedForImplementation {
get { return false; }
}
}
and state factory interface is defined like this:
public interface IStateFactory {
AbstractState GetState(String state);
}
the final thought is to put the method:
public void AlterState(String stateString) {
this.state = stateFactory.GetState(stateString);
}
Is the design ok? what are the cons and pros?
What about extensibility? From my perspective one can extend/implement its own state factory. But if there's a change in AbstractState itself everything changes accordingly.
Thanks!
You maybe interested in Stateless, a hierarchical state machine by Nicholas Blumhardt. Read this my SO answer here regarding it's capability. Here is a simple workflow processor example from my blog, and I currently use it with the Pipe and Filter pattern, and it works quite nicely.
Edit
I also have an implementation that uses Stateless with RavenDB if you are interested.
CQRS and the state pattern are completely different things. The state pattern provides a way to implement a set of states or statuses for a single object whereas CQRS is an architectural style. MVC has nothing to do with the state pattern nor CQRS and is an architectural style for the presentation layer. You can use the state pattern in conjunction with NHibernate, however the mapping will be non-trivial and you will have to implement a custom IUserType to map to the appropriate state class based on fields. RavenDB is very different from NHibernate and mapping will be quite a bit easier with it, but it is a completely different database system.
CQRS would be if you were using sql to back an admin tool, and RavenDB for the front end to run searches. You would need to push data to RavenDB from Sql in this fictional CQRS scenario.

Dynamically assigning a Domain Model within a Domain Model

This is my first question, and I've agonised over what to write for a couple of days while Ive been trying to solve this problem.
I bought the Dependency Injection in .NET book by Mark Seeman, and have been trying to follow that and the examples on the Ninject website for creating an abstract factory class. The general idea is that I have a form contains a list of answers to questions. Answers can be of various types, so I am using a factory to create the relevant answer type.
I'm getting the error:
Error activating IAnswerValue
No matching bindings are available, and the type is not self-bindable.
Activation path:
1) Request for IAnswerValue
Suggestions:
1) Ensure that you have defined a binding for IAnswerValue.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
I initially tried with a parameter, but to simplify things for this example, Ive stripped it all out. None of the suggestions given in the error message seem to apply, the factory type is binding, as is the form service but the answervalue is apparently not.
This is the code from my NinjectWebCommon.cs
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.AnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.StringAnswerValue>();
kernel.Bind<DomainModel.IAnswerValue>().To<DomainModel.DateTimeAnswerValue>();
kernel.Bind<IAnswerValueFactory>().ToFactory();
This is the answer class definition:
public class Answer
{
readonly IAnswerValueFactory answerValueFactory;
public int Id { get; set; }
public Question Question { get; set; }
public string Type { get; set; }
public Answer(IAnswerValueFactory answerValueFactory)
{
this.answerValueFactory = answerValueFactory;
}
public void GetAnswerValue()
{
var answer = this.answerValueFactory.GetAnswerValue();
}
public List<AnswerItem> PotentialAnswers { get; set; }
}
and the answer value:
public interface IAnswerValue
{
AnswerValue GetAnswerValue();
}
public class AnswerValue : IAnswerValue
{
readonly IAnswerValue answerValue;
public AnswerValue() { }
public AnswerValue(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public AnswerValue GetAnswerValue()
{
// this will contain a switch statement to
// determine the type returned but I have
// omitted for this example
return new StringAnswerValue();
}
}
public class StringAnswerValue : AnswerValue
{
public string StringAnswer { get; set; }
}
and the factory:
public class AnswerValueFactory : IAnswerValueFactory
{
readonly IAnswerValue answerValue;
public AnswerValueFactory(IAnswerValue answerValue)
{
this.answerValue = answerValue;
}
public IAnswerValue GetAnswerValue()
{
return (IAnswerValue)this.answerValue.GetAnswerValue();
}
}
I feel like Ive exhausted my knowledge and Im just going around in circles trying the same thing over and over. There must be something quite simple Im missing, but I just cant see what it is.

Resources