Dependency Injection doesn't know about type that I want to inject

I want to use HaveBox for Dependency Injection. But it isn't question about HaveBox. So I created base controller:

public abstract class BaseController : Controller
    {
        protected  readonly IRepository m_Repository;

        protected BaseController(IRepository repository)
        {
            m_Repository = repository;
        }
    }

And my HomeController was inherited from BaseController . Add HaveBoxConfig.RegisterTypes(); to Application_Start method and implementation of HaveBoxConfig is:

 public class HaveBoxConfig
    {
        public static void RegisterTypes()
        {
            var container = new Container();
            container.Configure(config => config.For<IService>().Use<Service>());
            container.Configure(config => config.For<IRepository>().Use<Repository>());
            IDependencyResolver resolver = DependencyResolver.Current;
            var newResolver = new MyResolver(container, resolver);
            DependencyResolver.SetResolver(newResolver);
        }
    }

And my resolver:

public class MyResolver : IDependencyResolver
    {
        private readonly IContainer m_container;
        private readonly IDependencyResolver m_resolver;
        public MyResolver(IContainer container, IDependencyResolver resolver)
        {
            m_container = container;
            m_resolver = resolver;
        }
        public object GetService(Type serviceType)
        {
            try
            {
                return m_container.GetInstance(serviceType);
            }
            catch (Exception ex)
            {
                return m_resolver.GetService(serviceType);
            }
        }
        public IEnumerable<object> GetServices(Type serviceType)
        {
            return m_resolver.GetServices(serviceType);
        }
    }

Method GetService called for next types: IControllerFactory , IControllerActivator , HomeController but not for my IRepository .

What am I doing wrong? Why DI isn't executed for IRepository ?


You also need to implement a controller factory. Easiest way is to subclass DefaultControllerFactory. You can check how they do it with Castle Windsor. Then you tell ASP.NET MVC to use your implementation.

DependencyResolver.SetResolver(newResolver);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);

I have checked different ways to solve it. Most simple is just add my controllers to container. For example:

container.Configure(config => config.For<HomeController>().Use<HomeController>());

It is simple and clear. If you have complex project and for more graceful solution you can do it via reflection for all classes that implemented IController interface.

链接地址: http://www.djcxy.com/p/76194.html

上一篇: java.lang.NullPointerException:Java初学者

下一篇: 依赖注入不知道我想要注入的类型