Keeping dependency inject component out of main code base - dependency-injection

I have a MVC app that uses ninject to inject service dependencies into controllers and it works well. However I also have some domain objects that require these services in their constructors and I want to resolve these dependencies using ninject, but don't want to reference ninject directly in my domain objects assembly. I have read lots of questions and answers here but its still not clear to me the best way to go about this. For example I have a ShoppingCart domain object that needs an instance of a IProductCatalogService passed to its constructor. What is the best pattern to create an instance of a shopping cart? I could have a reference to the root kernel and call out to that, but that would mean having references to ninject throughout my domain assembly. Should I wrap access to the kernel in a factory class?
Any thoughts or suggestions welcome!

It is usually considered bad practice to have services in domain objects. I think you need to rethink exactly what you are attempting to achieve. Why does a ShoppingCart need to consume Product Catalog Services?
From a Domain perspective I would assume that a ShoppingCart would consist of many 'items', have properties like total etc and potentially would be passed to an ordering service. Your controller actions would update the Shopping Cart domain by adding items, removing items, etc, etc.
If you really need to consider this option, is to use commonservicelocator. This will separate out your (direct) dependency on ninject.

Related

ASP.NET MVC - DbContext good practices

I'm starting a new .NET MVC project with Entity Framework and I am struggling with some problems.
In my model I have about 150 entities (generated from the database). Is it a good idea to have only one DbContext? If not, how should I divide my entities?
If I have one DbContext and I create a class variable that instantiates a database context object (in Controller), what happens then with this DbContext? Does it create in memory separate space for each of my entities? In my case, when I have 150 entities it would not be very effective. Am I wrong?
I will be using my DbContext in many Controllers. Is it a good idea to create a MainController (where I create new DbContext), which will be inherited by the rest of the Controllers? Because this allows others to have access to the same Context.
What is the best practise for disposing my DbContext? I've read that it is good practice to use dependency injection. But in this way I will have to inject context to every of my controllers. Which dependency injection way is the most popular and used now?
Really need your advice. It will give me more insight to this piece of development.
It is fine to have one DbContext. If you have many you just need to ensure all the entities you need exist in the that context. For example, if you retrieve a Person from the database and their related Address, then both the Person and Address have to exist in the same DbContext.
I've not tried using multiple DbContext instances, but one thing to look out for is if you include the same table in multiple contexts you could end up with classes with similar names or maybe conflicts. For example, if you include Person in two contexts, then each context will attempt to create a class named Person.
When you create a DbContext it will only create objects for the data you retrieve from the database. So if you request one row from a Person table, then only one Person object will be created. If you request 100 rows, then 100 instances will be created.
There are really two options. One, create a new instance in each action, do your work, then save it. Or, create a DbContext in your constructor and reuse that throughout the class.
This depends one what you choose in point #3. If you pass it into the constructor, then implement IDisposable and release it in there. If you create a new one in each action, then ensure it gets disposed using the using statement.
For dependency injection there are a number of options, tutorials, etc, on how to do this in ASP.NET MVC. I personally use Autofac, and related MVC extensions, and pass a new instance of the DbContext into each controller.
150 Entities is not a huge DbContext, but it is above the size where EF starts to exhibit performance issues in the initialization of the first DbContext. If you can logically separate your entities into areas of responsibility (called a bounded context) then you might consider using more than one DbContext. Also, does your app need to use all those entities? If not, you may be able to simplify things. Also note, you need at least EF6 to make this work effectively, previous versions of Entity Framework had issues with multiple contexts.
You also have to be careful when using multiple contexts. Many people get into trouble because they get an entity from one context, but then call save changes on a different one, and then don't understand why their changes are not saved. Or, they try to add an entity retrieved from one to another, which you can't do. Multiple contexts make things more complicated, so make sure you want to take on that complexity before you split it up.
Don't worry about the amount of memory your DbContext uses, so long as you are properly disposing of it. The amount of memory will be minimal unless you actually load objects from all of those tables.
I consider a common base controller to be a code smell. It's usually completely unnecessary, and it usually ends up becoming a dumping ground for every piece of code you think you want to share, which violates the Single Responsibility Principal. On top of that, you shouldn't be doing data access in your controllers anyways. You should have a service layer of some sort or business layer that call into a data access layer. Properly segregating your concerns is a key part of designing a good MVC application.
Yes, Dependency Injection is a good practice. I'm not sure what you mean by "have to inject into all my controllers". The whole point of dependency injection is to inject your dependencies, so the concept of "having to" makes it seem like you're trying to avoid the very thing you're trying to do.
Dependency Injection is a principle. There are many ways to achieve this principle, and which way you use depends entirely on your own preferences and requirements. We can't tell you what's "best" other than to make sure you're following the principle, and not a specific technology.
Regarding the dbcontext question:
I would go with multiple dbcontext (bounded contexts).
One problem with single big dbcontext is the loading and the Initializing time as it will map all the entities and this increases when your entities number increase in your context.
Now your project must consist of modules and this where you can divide your big dbcontext into small db contexts that covers all what each individual module needs to work with the database, for example let's say that your project has two modules (membership and billing or financial) for customer/person entity, you will find that when you deal with person in the membership module you need all his details but not full details of his invoices, and when you deal with the person in the billing module you will need all his invoices deatils but not his full personal information, here you can create 2 dbcontexts one for each module with person entity contains what that module needs from the person entity.
Julie lerman has a good article about dbcontext with Entity-framework that start with to get more details about what I am trying to describe here,
https://msdn.microsoft.com/en-us/magazine/jj883952.aspx
Hope this helps

Dependency Injection - Passing dependencies all the way down

I have an MVC application with a typical architecture...
ASP.NET MVC Controller -> Person Service -> Person Repository -> Entity Framework DB Context
I am using Castle Windsor and I can see the benefit of using this along with a ControllerFactory to create controller with the right dependencies. Using this approach the Controller gets a Service injected, which in turn knows how to construct the right Repository, which in turn knows the correct DbContext to use.
The windsor config is something like this...
dicontainer = new WindsorContainer();
dicontainer.Register(Component.For<IPersonService>().ImplementedBy<PersonService>());
dicontainer.Register(
Component.For<IPersonRepository>().UsingFactoryMethod(
() => new PersonRepository(new HrContext("connectionString"))));
It this the right way to do it? I don't like the UsingFactoryMethod, but can't think of another way.
Also, what if the Repository needed a dependency (say ILogger) that was not needed by the service layer? Does this mean I have to pass the ILogger into the service layer and not use it. This seems like a poor design. I'd appreciate some pointers here. I have read loads of articles, but not found a concrete example to verify whether I am doing this right. Thanks.
I try to avoid using factory methods (as you mentioned you felt this smelled funny). To avoid this, you could create a database session object that creates a new DbContext. Then your repositories just need to get an instance of IDbSession and use its dbContext property. Then, you can also easily control the scope of the IDbSession object (don't use singleton because it's not thread safe).
I wanted to make that point so that I could make this more important point... Make your constructors take in only objects that are registered in the DI container (no options or configurations in constructors). Options and configurations should be read/writen in classes whose sole purposes it is to read/write those values. If all classes follow this model, then your DI registration becomes easy and classes can just add whatever dependencies they need in their constructors.
If you are trying to use a third party library that has options in constructors, wrap that class in your own class that has an easy to consume constructor and uses a configuration class to read the values needed to pass to the third party library. This design also introduces a layer of abstraction between your code and the third party library which can then be used to more easily swap (or stub) third party libraries when necessary.

Dependency Inject for models

I'm sure someone has asked this before, but I'm struggling to find where.
I'm using Ninject to remove dependencies from my controllers, along with a repository design pattern.
As I understand it, one of the benefits of this approach is that I can easily whip apart my repositories and domain entities and use another assembly should I so wish. Consequently I've kept my domain entities and repositories in external assemblies and can mock all my dependencies from interfaces.
It seems that while I can use interfaces to refer to my domain entities in most places I must use references to my concrete classes when it comes to model binding. I've read that this is to do with serialization which I understand, but is the only way to avoid referring to domain entities to create separate models?
Anything I can do with Custom Model Binding?
A bit of background: I'm an experienced ASP.net developer, but new to MVC.
View Models should be plain data containers with no logic and therefore shouldn't have any dependencies at all. Instead inject the repositories to your controller and have it assign the required data from the repository to the appropriate property of your view model.
The major advantage of using a dependency injection framework is IoC (Inversion of Control):
loosely coupling
more flexibility
easier testing
So what one usually does is to inject repositories through their interfaces like
public class MyController : Controller
{
private IPersonRepository personRepo;
public MyController(IPersonRepository personRepo)
{
this.personRepo = personRepo;
}
...
}
During testing this allows to easily inject my mock repository which returns exactly those values I want to test.
Injecting domain entities doesn't make that much sense as they are more tightly linked with the functionality in the specific class/controller and thus abstracting them further would just be an overhead rather than being a benefit. Instead, if you want to decouple your actual entity model from the controller you might take a look at the MVVM pattern, creating specialized "ViewModels".
Just think in terms of testability of your controller: "What would I want to mock out to unit test it?"
DB accesses -> the repository
External dependencies -> other BL classes, WS calls etc.
I wouldn't include domain entities here as they're normally just a data container.
Some more details would help. A bit of code perhaps?
To start with, you should avoid injecting dependencies into domain entities, but rather use domain services.
Some more info here.
Edit 001:
I think we should clarify our terminology.
There is the domain layer with all you domain entities, e.g. product, category etc.
Then there's the Data Layer with your repositories that hydrate your domain entities and then you have a Service Layer with you application services that talks to the data layer.
Finally you have a presentation layer with your views and controllers. The Controllers talk to you Aplication Service Layer. So a Product Controller talks to a Catalogue Service (e.g. GetProductBySku). The CatalogueService will have one or more repositories injected into its constructor (IProductRepository, ICategoryRepository etc.).
It's quite common in asp.net mvc to have ViewModels too. Put the ViewModels in your Application Service Layer.
So I'm not sure what you mean when you say "models" and "domain enntities" but I hope that clears up the terminology.

Dependency Injection: How to inject when using a multi-project solution

hope this question is not all too stupid, I'm trying to get a hold of more advanced programming principles and was thus trying to get used to Dependency Injection using Ninject.
So, my model is split up into several different .dll-projects. One project defines the model specifications (Interfaces) and a couple of others implement these interfaces. All model projects need to use some sort of database system, so they all need access to yet another .dll which implements all my database logic. It is important that all of them can access the same instance of my database object, though, so if wouldn't suffice to just create one instance for each model.
I'm not quite sure how to achieve this using dependency injection, though. My first thought was to create a seperate DI-project and bind all interfaces to their respective implementation, so the DI-project needed references to all the other projects (model interfaces & implementations, database system etc.). Then again, the models would need access to the DI project since, for example, they'd need to request the database system from the DI System (Ninject). Of course this would create a circular reference (binding DI project to model and model to DI project), so it's not possible.
Long story short, I'd need a programming pattern that allows me to bind model interfaces to their implementations but that also allows the model implementations to request other dependencies from Ninject, e.g.
IModel1 -> Model1
IModel2 -> Model2 (different project)
IDatabase -> Database (different project)
Model1 -> request IDatabase -> get Database instance
Model2 -> request IDatabase -> get the same Database instance
Would be glad to get a couple of suggestions, at the moment I'm stuck and out of ideas ;)
Thanks!
the models would need access to the DI project since, for example,
they'd need to request the database system from the DI System
(Ninject)
When you use dependency injection, the model shouldn't need to access the DI framework, since it is the DI framework that injects dependencies. The model objects should not be asking the DI container. When the your objects are asking the container for dependencies it is not called Dependency Injection, but Service Locator. Service Locator is an anti-pattern.
My first thought was to create a seperate DI-project
When you have a single application (e.g. a web app), the usual thing to do is completely configure the DI container in the startup project, as close as possible to the application’s entry point. This entry point where all object graphs are composed is called the Composition Root.
All model projects need to use some sort of database system, so they
all need access to yet another .dll which implements all my database
logic
Try making POCO (plain old CLR objects) model/entity objects, or at least, ensure that those objects don't need to reference any other project, which makes your architecture (and testing) much easier.
Use Ninject with the Register Resolve Release pattern from within a Composition Root.
The client application would use Ninject to inject the actual database and model implementations.
The client application therefore needs to reference the database, idatabase, model and imodel projects.
The idatabase and database projects need to reference the model project, as the methods will return model objects or collections of model objects. Have a look at the repository pattern.
Your model doesn't need to reference any of your projects.

Can a pure DDD approach be used with NHibernate?

I've been reading up on DDD a little bit, and I am confused how this would fit in when using an ORM like NHibernate.
Right now I have a .NET MVC application with fairly "fat" controllers, and I'm trying to figure out how best to fix that. Moving this business logic into the model layer would be the best way to do this, but I am unsure how one would do that.
My application is set up so that NHibernate's session is managed by an HttpModule (gets session / transaction out of my way), which is used by repositories that return the entity objects (Think S#arp arch... turns out a really duplicated a lot of their functionality in this). These repositories are used by DataServices, which right now are just wrappers around the Repositories (one-to-one mapping between them, e.g. UserDataService takes a UserRepository, or actually a Repository). These DataServices right now only ensure that data annotations decorating the entity classes are checked when saving / updating.
In this way, my entities are really just data objects, but do not contain any real logic. While I could put some things in the entity classes (e.g. an "Approve" method), when that action needs to do something like sending an e-mail, or touching other non-related objects, or, for instance, checking to see if there are any users that have the same e-mail before approving, etc., then the entity would need access to other repositories, etc. Injecting these with an IoC wouldn't work with NHibernate, so you'd have to use a factory pattern I'm assuming to get these. I don't see how you would mock those in tests though.
So the next most logical way to do it, I would think, would be to essentially have a service per controller, and extract all of the work being done in the controller currently into methods in each service. I would think that this is breaking with the DDD idea though, as the logic is now no longer contained in the actual model objects.
The other way of looking at that I guess is that each of those services forms a single model with the data object that it works against (Separation of data storage fields and the logic that operates on it), but I just wanted to see what others are doing to solve the "fat controller" issue with DDD while using an ORM like NHibernate that works by returning populated data objects, and the repository model.
Updated
I guess my problem is how I'm looking at this: NHibernate seems to put business objects (entities) at the bottom of the stack, which repositories then act on. The repositories are used by services which may use multiple repositories and other services (email, file access) to do things. I.e: App > Services > Repositories > Business Objects
The pure DDD approach I'm reading about seems to reflect an Active Record bias, where the CRUD functions exist in the business objects (This I call User.Delete directly instead of Repository.Delete from a service), and the actual business object handles the logic of things that need to be done in this instance (Like emailing the user, and deleting files belonging to the user, etc.). I.e. App > (Services) > Business Objects > Repositories
With NHibernate, it seems I would be better off using the first approach given the way NHibernate functions, and I am looking for confirmation on my logic. Or if I'm just confused, some clarification on how this layered approach is supposed to work. My understanding is that if I have an "Approve" method that updates the User model, persists it, and lets say, emails a few people, that this method should go on the User entity object, but to allow for proper IoC so I can inject the messagingService, I need to do this in my service layer instead of on the User object.
From a "multiple UI" point of view this makes sense, as the logic to do things is taken out of my UI layer (MVC), and put into these services... but I'm essentially just factoring the logic out to another class instead of doing it directly in the controller, and if I am not ever going to have any other UI's involved, then I've just traded a "fat controller" for a "fat service", since the service is essentially going to encapsulate a method per controller action to do it's work.
DDD does not have an Active Record slant. Delete is not a method that should be on an Entity (like User) in DDD.
NHibernate does support a DDD approach very well, because of how completely divorced it remains from your entity classes.
when that action needs to do something
like sending an e-mail, or touching
other non-related objects
One piece of the puzzle it seems you are missing is Domain Events. A domain entity shouldn't send an email directly. It should raise an event in the Domain that some significant event has happened. Implement a class whose purpose is to send the email when the event occurs, and register it to listen for the Domain Event.
or, for instance, checking to see if
there are any users that have the same
e-mail before approving
This should probably be checked before submitting the call to "approve," rather than in the function that does the approving. Push the decision up a level in calling code.
So the next most logical way to do it,
I would think, would be to essentially
have a service per controller
This can work, if it's done with the understanding that the service is an entry point for the client. The service's purpose here is to take in parameters in a DTO from the front end/client and translate that into method calls against an entity in order to perform the desired funcitonality.
The only limitations NHibernate creates for classes is all methods/properties must be virtual and a class must have a default constructor (can be internal or protected). Otherwise, it does not [edit] interfere with object structure and can map to pretty complex models.
The short answer to you question is yes, in fact, I find NHibernate enhances DDD - you can focus on developing (and altering) your domain model with a code first approach, then easily retro-fit persistence later using NHibernate.
As you build out your domain model following DDD, I would expect that much of the business logic that's found you way into you MVC controllers should probably reside in your domain objects. In my first attempt at using ASP.NET MVC I quickly found myself in the same position as yourself - fat controllers and an anemic domain model.
To avoid this, I'm now following the approach of keeping a rich domain model that implements the business logic and using MVC's model as essentially simple data objects used by my views. This simplifies my controllers - they interact with my domain model and provide simple data objects (from the MVC model) to the views.
Updated
The pure DDD approach I'm reading about seems to reflect an Active Record bias...
To me the active record pattern means entities are aware of their persistance mechanism and an entity maps directly to a database table record. This is one way of using NHibernate e.g. see Castle Active Record, however, I find this pollutes domain enitities with knowledge of their persistence mechanism. Instead, typically, I'll have a repository per aggregate root in my domain model which implements an abstract repository. The abstract repository provides basic CRUD methods such as:
public IList<TEntity> GetAll()
public TEntity GetById(int id)
public void SaveOrUpdate(TEntity entity)
public void Delete(TEntity entity)
.. which my concrete repositories can supplement/extend.
See this post on The NHibernate FAQ which I've based a lot of my stuff on. Also remember, NHibernate (depending on how you set up your mappings) will allow you to de-persist a complete object graph, i.e. your aggregate root plus all the objects hanging off it and once you've finished working with it, can cascade saves through you entire object graph, this certainly isn't active record.
...since the service is essentially going to encapsulate a method per controller action to do it's work...
I still think you should consider what functionality that you currently have in your controllers should, more logically, be implemented within your domain objects. e.g. in your approval example, I think it would be sensible for an entity to expose an approve method which does whatever it needs to do to within the entity and if, as in your example, needs to send emails, delegate this to a service. Services should be reserved for cross-cutting concerns. Then, once you've finished working with your domain objects, pass them back to your repository to persist changes.
A couple of books I've found useful on these topics are:
Domain-Driven Design by Eric Evans
Applying Domain-Driven Design and Patterns by Jimmy Nilsson

Resources