Unable to inject with unity a complex type to web

2019-09-18 18:21发布

问题:

I have a complex type to inject into a webapi controller and I am unable to resolve this dependency

 public class MyController(IMyComplexType)

The implementation of IMyComplexType has at least 5 dependencies I1, ... I5(so its implementation recieve I1...I5)

I have a Bootstrapper class to Register all dependencies, below a snippet of code to show you

    public class Bootstrapper
    {
        public static IUnityContainer ConfigureContainer(ref IUnityContainer container)
        {
            container.RegisterType<IMyComplexType, MyComplexTypeImplementation>
            (
              new HierarchicalLifetimeManager()
            );

            //Registering I1...I5 in the same way with their implementations
        }
     }

I tried to Load the Assmebly directly, so I1...I5 reside in assembly1, at the begining of my ConfigureContainer method

Assembly.Load("assembly1");

Also I have a UnityResolver copied from: WebApi dependency injection

This is my WebApiConfig:

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            IUnityContainer container = new UnityContainer();
            Bootstrapper.ConfigureContainer(ref container);
            config.DependencyResolver = new UnityResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

I tried also to remove the injecton constructor on my controller and inside the Post method put something like this:

var service = Container.Resolve<IMyComplexType>() or var service = Container.Resolve<MyComplexTypeImplementation>()

I am losing something here?

回答1:

Register all constructor types first and then the rest.

HttpContext.Current.Application.SetContainer(container);
container.AddNewExtension<Interception>();
c.RegisterType<IYourType,YourType>();
...
futher constructor types here
...
c.RegisterType<IMyComplexType,MyComplexType>();

c.RegisterType<IMyController, MyController>(
            new HierarchicalLifetimeManager(), 
            new InjectionConstructor(typeof(IMyComplexType)));

and then

public static class WebApiBootstrapper
    {
        public static void Init(IUnityContainer container)
        {
            GlobalConfiguration.Configure(config =>
            {
                config.DependencyResolver = new WebApiDependencyResolver(container); // DI container for use in WebApi
                config.MapHttpAttributeRoutes();
                WebApiRouteConfig.RegisterRoutes(RouteTable.Routes);
            });
        }
    }