ASP.NET MVC3 - Use DependencyResolver AND Windsor Castle: Why?

可紊 提交于 2019-12-12 16:31:32

问题


Can somebody shine a little light for me?

I've got my website all running using Windsor Castle. I have a controller factory and installers for controllers and services. All nice.

Now I've just created a IDependencyResolver implementing class called WindsorDependencyResolver with a straigh-forward implementation:

public class WindsorDependencyResolver : System.Web.Mvc.IDependencyResolver
{
    private readonly IKernel _kernel;

    public WindsorDependencyResolver (IKernel kernel)
    {
        _kernel = kernel;
    }

    public object GetService(Type serviceType)
    {
        return _kernel.Resolve(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _kernel.ResolveAll(serviceType) as IEnumerable<object>;
    }
}

I've got it setup like so (global.asax):

DependencyResolver.SetResolver(new WindsorDependencyResolver(kernel));

And now what? When is this 'used'? Should I stop using kernel.Resolve(someType)?


回答1:


My understanding is the IDependencyResolver is what is used internally by MVC 3 to do Service Location/Inversion of Control. So in order for your Controllers to get instantiated properly, and be able to inject whatever dependencies you have, you need to tell MVC how to talk to the container your using (Windsor in your case).

You would still want to use kernel.Resolve(someType) when you need to get something out of the container that is not injected for you via constructor/property injection.

Interestingly, the MSDN documentation points to Brad Wilson's Blog Post on the IDependencyResolver for details.




回答2:


It sounds like you already have a custom IControllerFactory. If so, just stick with it. It's a much better solution than the hack that is IDependencyResolver (which has lots of problems).



来源:https://stackoverflow.com/questions/6168421/asp-net-mvc3-use-dependencyresolver-and-windsor-castle-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!