How to use dependency injection with ASP.NET MVC model?

I would like to add a dependency to the ASP.NET MVC model, but I cannot figure out where in the process to inject.

It's very easy with ControllerFactory, but not so much when it comes to models.

+2


source to share


7 replies


I ended up creating a service locator: http://martinfowler.com/articles/injection.html#UsingAServiceLocator



It's getting easier for me than dealing with an IoC container and trying to inject my DI code throughout the MVC pipeline.

0


source


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



0


source


I usually install dependencies in the controller, for example

PersonController(IPersonRepository r)
{
\\ constrtuctor code
}

      

in models, maybe when you need some instance of something that inherits an interface, you do something like this:

var r = container.Resolve<IPersonRepository>();

      

0


source


I would recommend considering the S # arp architecture http://www.sharparchitecture.net/

An open source environment for asp.net mvc.

0


source


Are you completely sure that you need to inject a dependency into your domain model? An object or business object usually encapsulates state and exposes methods to change that state according to business rules. Code that doesn't fall into this category is usually found in a service. Have you read the concept of a domain service at all ? Perhaps using one will better suit your needs and you won't need to inject any dependencies into your domain.

0


source


Checkout this sample that I created based on Ayende's explanations on his blog. Basically, I'm using Castle as my IoC container, and I'm using Mvc Contrib to add all the controllers to the container and make Mvc get them from it. Then I can inject anything into containers like ISIBernate ISession.

If you want to inject stuff inside your model classes (objects), NH now supports Including Hibernate Managed Object Dependencies . See this , this and this for specific examples for Spring and Windsor.

0


source


What do you say more on the lines of the Active Record template.

Whether AR is possible or not depends on which ORM / DAO you are using.

The AR model is usually better suited for small projects.

0


source







All Articles