开发者

How do I use dependency injection with an ASP.NET MVC model?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜