How do I use dependency injection with an ASP.NET MVC model? - asp.net-mvc

I would like to inject a dependency into an ASP.NET MVC model, but I can't figure out where in the pipeline to do the injection.
It's very straightforward with a ControllerFactory, but not nearly as much when dealing with models.

You can find a reasonable How-To on Shiju Vargheses Blog: ASP.NET MVC Tip: Dependency Injection with Unity Application Block

usually i inject dependencies in the controller like this
PersonController(IPersonRepository r)
{
\\ constrtuctor code
}
in the models probably when need some instance of something that inherits an interface you do something like this :
var r = container.Resolve<IPersonRepository>();

I ended up creating a service locator: http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I find it easier than dealing with an IoC container and trying to insert my DI code all over the MVC pipeline.

I'd recommend reviewing S#arp Architecture
http://www.sharparchitecture.net/
Open source framework addon for asp.net mvc.

Are you completely sure you need to inject a dependency into your domain model itself? An entity or business object will typically encapsulate the state and expose methods to modify that state according to business rules. Code that does not fall into this category typically will be found in a service. Have you read into the concept of a domain service at all? Perhaps using one would better suit your needs and you won't need to inject any dependencies into your domain itself.

Checkout this sample I've created based on Ayende's explanations on his blog. Basically, I use Castle as my IoC container and I use Mvc Contrib to add all controllers to the container and make Mvc get them from it. Then I can inject anything into the containers, such as NHibernate ISession.
If you want to inject stuff inside your model classes (entities), NH now supports Dependency Injection of Hibernate-managed objects. See this, this, and this for specific examples for Spring and Windsor.

What your talking about is more along the lines of the Active Record pattern.
Whether AR is possible or not will depend on which ORM/DAO your using.
The AR pattern is generally better suited for small projects.

Related

Dependency Injection in .net core, Autofac vs StructureMap vs Factory Method to resolve interface if registered with multiple implementation

In my project I using chain of responsibility designing pattern for which I need to create multiple handlers which will implement same interface. In .net application(not .net core) I would have used DI using UnityContainer where I could have resolved handlers using named parameter. But in .net core I can not do that. Now I have few options to use other DI libraries like Autofac, Structuremap or create factory method which can give me objects based on name passed. Please help me in picking right approach between these or suggest something better if available. I have not used Autofac or Structuremap so I very little idea of same. Thanks.
For the most part, all DI tools out there achieve the same thing with different APIs. These days the differences are highlighted by your needs.
StructureMap or Autofac are both good candidates. It all boils down to "flavor".
Check this article. I think is a good one. Configuration comparison dependency injection containers
Again, don't stress over them unless you need a very very specific feature form one of them.
I would do Autofac just because I haven't had the need for something else however, I would not hesitate to use StructureMap, Ninject or whatever new kid on the block is brought up.

Is Dependency Injection a must in asp.net MVC?

I am currently viewing multiple tutorials (and reading books) to start working with ASP.NET MVC.
I see that ninject (or similar) is widely used to implement Dependency injection and from what i understood the main issue here is resource allocation from the classes i need.
We want to be sure for example that we have only one instance of the repo object.
I need to learn first things first so i am interested in knowing how i would create an ASP.NET MVC without using DI techniques and still be correct as far as my object resources are concerned
More info:
I have made some winforms applications. These apps where using a Business Layer DLL (BLL). This BLL had access to my DAL DLL (plain ADO.NET). they are working quite well..
No i want to use the SAME BLL to MVC apps.
With injection or not?
Without injection implementation?
Do i just create the BLL object in my controller constructor and that's all?
ASP.NET MVC doesn't require you to use dependency injection at all. It will work perfectly fine if all of your controllers have default constructors. On the other hand, you will be responsible for creating the objects and managing their lifetimes. If you need to have one repository object for the application, you have to manually implement its lifecycle(using a static variable or Singleton pattern).
If you care about testing, using dependency injection will certainly help you to design more testable and reusable objects. You can easily replace the dependencies with test doubles in your test code and let DI container inject the real implementations in the runtime.
If you are sure about not using it, then make sure all of your controllers have default constructors. You don't need any configuration.
Dependency Injection is not a requirement for using ASP.net MVC. You can definitely build an MVC app without it.
Where it will come in handy is if you want to perform unit testing on your application. If you would like to unit test an action in a controller, if you have DI set up, then you can mock your dependencies that are included in the controller constructor (that DI takes care of when the app is running) and set up responses to return when they are called by the Action.
This is much harder and impractical (if not impossible) to do if you are not using Dependency Injection. In such a case, if you want to use Unit Testing, it will be very hard to write pure unit tests of your Actions, since you will have no easy way to mock your service and data access layers for your tests.
And as you wrote, the DI layer will also enable you to ensure things like having only one instance of the repository objects that you are injecting, etc.

Advice on isolating my nhibernate layer such that I could swap it out with EF potentially

Ok it seems my project setup could use some improvments.
I currently have:
1. ASP.NET MVC3 Web project
2. NHibernate project with Repositories/Mappings and some session code.
3. Entities (models used in nhibernate like User.cs)
4. Interfaces (like IUser, IRepository<IUser>, IUserRepository...)
5. Common (UserService, ..)
Now the issue is that I my nhibernate models now need to implement IUser, which I don't like, but I was forced to do this since my IRepository is generic, and I could use IRepository<User> since User is in another project, so I had to create an interface and do IRepository<IUser>
I will never need to have another implemention of User, so this is bugging me.
How can I fix this while keeping things seperate so I can swap out my ORM?
The IUser interface must be defined in the Entities layer if your entities implement it, not in the Interfaces layer. Also I would probably rename this generic Interfaces layer to Repositories or AbstractRepositories or something. Also I would rename the Common layer to Services if it contains services aggregating your repositories.
So the picture could be:
ASP.NET MVC3 Web project
NHibernate project with Repositories/Mappings and some session code.
Domain Entities (models used in nhibernate like User.cs and implementing domain interfaces like IUser)
Repositories (like IRepository<IUser>, IUserRepository...)
Services (UserService, ..)
I think you should approach this problem from Domain Driven Design perspective. Domain should be persistent-ignorant. Proper implementation of DDD repository is a key here. Repository interface is specific, business-focused, not generic. Repository implementation encapsulates all the data access technicalities (ORM). Please take a look a this answer and these 2 articles:
How to write a repository
DDD: The Generic Repository
Your entities should be concrete types, not interfaces. Although you may never need to swap your ORM (as Ladislav is saying in comments), you should design it as if you will need to swap it. This mindset will really help you achieve persistence ignorance.

StructureMap and MVC 3.0

Has anyone used structuremap with the new DI features of asp.net mvc 3.0? If so, could you post some example code or some links to examples that have been helpful? In attempting to learn ASP.NET MVC 3, I am trying to make sure I use all the "new" features and am struggling with integrating a IoC container.
As others mentioned you'd want to look at Common Service Locator (CSL) that is a simple service resolution facade around any container (any of your choice).
MVC3 internally heavily uses the new IDependencyResolver interface which is somewhat like CSL but in ASP.NET MVC context. The good thing is that if you are already using CSL then you can set it as Dependency Resolver for MVC.
This topic is equally essential for any container and not specific to StructureMap.
So what is going on there:
You provide all necessary container registrations (preferrably through Registry DSL in case of StructureMap);
You get the StructureMap adapter for Common Service Locator;
You (optionally - if you need CSL along with DependencyResolver) register your StructureMap adapter as current Service Locator:
ServiceLocator.SetLocatorProvider(() => yourStructureMapAdapter)
You register your CSL (backed by StructureMap) as MVC DependencyResolver:
DependencyResolver.SetResolver(yourStructureMapAdapter)
MVC3 automatically wires everything up through IDependencyResolver interface internally (using all StrucutreMap DI auto-wiring capabilities).
Along with MVC3 baked-in IoC capabilities, use the power of IoC tool at your disposal (e.g. use Assemblies scanning available in StructureMap) to max extent.
Ran into this the other day, may be helpful:
http://weblogs.asp.net/rashid/archive/2009/02/15/asp-net-mvc-unity-and-common-service-locator.aspx
I looked around a bit and this is the first Google result I got. It gives a good of what is new in MVC 3 service location: http://bradwilson.typepad.com/blog/2010/07/service-location-pt1-introduction.html
While it is dependent on a beta version of MVC 3, I am sure with some experimentation one can figure it out.
In a nutshell, it looks like they added some interfaces and extension methods that you can use to call StructureMap, or whatever your preferred IoC library is.
Update:
I just happened upon this link in the blogs I subscribe to. It has some good-looking sample code.
http://stevesmithblog.com/blog/how-do-i-use-structuremap-with-asp-net-mvc-3/

Ways of implementing Unit of Work in ASP.NET MVC

I'm currently researching how to add the Unit of Work pattern to my existing ASP.NET MVC application that uses NHibernate. I'm seeing a lot of variety in the various implementations and I'm having trouble determining which methods will work best in a given situation.
To help, I thought I would ask the Stack Overflow community to list their favorite ways of implementing the Unit of Work pattern in their ASP.NET MVC applications.
Maybe you use IoC to instantiate an NHibernate session when you create your controller and then pass that on to the repository. Or maybe you create a unit of work class/interface. Don't hesitate to link to additional resources after you describe your approach.
Also, be sure to list any pros and cons associated with your method should they exist.
I implemented a Repository / UoW pattern around Entity Framework 4 POCO objects and it has turned out very well for us. We only expose the UoW to the Business/Service layer and have the Controller, or the Presenter in our case, to call these services to execute or retrieve data.
The pattern that we implemented used the following article as a guide: http://msdn.microsoft.com/en-us/library/ff714955.aspx
This is a fantastic guide on the subject which I have used to great success with unit tests
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Resources