开发者

ASP MVC DependencyResolver with UnityContainer for Unit testing

开发者 https://www.devze.com 2023-03-23 17:14 出处:网络
I\'m building an ASP MVC 3 application in which I use Unity as IOC container and I register it on the DependencyResolver.In my controller I can then do this:

I'm building an ASP MVC 3 application in which I use Unity as IOC container and I register it on the DependencyResolver. In my controller I can then do this:

DependencyResolver.Current.GetService(GetType(IViewAllPersonsHandler))

Then when I write my unit tests I redefine my mappings in my t开发者_开发问答est to use mocked objects.

A colleague of mine told me that doing this is considered as an Anti Pattern.

Can anyone tell me whether this is the case and why?

I know that normally I should inject my dependencies in the constructor, but as my controller grows the constructors parameters get lengthy.

Thx


Most folks consider the service locator pattern an anti-pattern. Probably since one can get around it with some leg-work.

If you are doing it to limit the constructor parameters you could try something different. I use property injection. Since I use castle windsor the container injects public properties by default. Last I looked Unity did not do this and you had to use some extension to get that to work.

Other than that you could split your controller or delegate to tasks within your actions.

But I would also stay away from service locator from within you controller.

HTH


You can use System.Web.Mvc.DependencyResolver.SetResolver(resovlveDependencyMock);


It's easy with Moq:

DependencyResolver.SetResolver(Mock.Of<IServiceLocator>(s => s.GetInstance(It.IsAny<Type>()) == cacheMock.Object));
0

精彩评论

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