asp.net unity dependency injection doesn't wor

2019-04-17 19:54发布

问题:

I am using the mvc 3 framework of asp.net, I have created a UnityControllerFactory that implements the IControllerFactory interface:

...
public class UnityControllerFactory : IControllerFactory
{
    private IUnityContainer _container;
    private IControllerFactory _innerFactory;

    public UnityControllerFactory(IUnityContainer container)
        : this(container, new DefaultControllerFactory())
    {
    }

    protected UnityControllerFactory(IUnityContainer container,
                                     IControllerFactory innerFactory)
    {
        _container = container;
        _innerFactory = innerFactory;
    }
public IController CreateController(RequestContext requestContext,
                                        string controllerName)
    {
        try
        {
            IController controller = _container.Resolve<IController>(controllerName.ToLowerInvariant);

            return controller;
        }
        catch (Exception ex)
        {
            var msg = ex.Message;
            return _innerFactory.CreateController(requestContext, controllerName);
        }

    }
...

and in the Application_Start(), I have:

protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);


        IUnityContainer container = GetUnityContainer();
        container.RegisterType<IRepository<User>, LiveRepository<User>>();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
        ...

    }

I test this with a home controller

public class HomeController : Controller{
    IRepository<User> userRepo;
    public HomeController(IRepository<User> userRepo)
    {
         this.userRepo = userRepo;
    }
    ...
}

When I run the app, I can not build the home controller at all. in the line:

IController controller = _container.Resolve<IController>(controllerName.ToLowerInvariant);

I get an exception says:

**"Resolution of the dependency failed, type = "System.Web.Mvc.IController", name = "homecontroller". Exception occurred while: while resolving.

Exception is: InvalidOperationException - The current type, System.Web.Mvc.IController, is an interface and cannot be constructed. Are you missing a type mapping?

At the time of the exception, the container was: Resolving System.Web.Mvc.IController,homecontroller"**

but even with the default controller factory using the line:

_innerFactory.CreateController(requestContext, controllerName);

I still cannot build the controller at all, please help

回答1:

I would recommend you taking a look at the following blog post which illustrates how to use a custom DependencyResolver with Unity in an ASP.NET MVC 3 application.