سؤال

I have a controller that has dependency injection.

Constructor of home controller:

    public HomeController(ICustomer customer, ISiteSettings siteSettings, ILogger logger, ILocalizer localizer)
        : base(customer, siteSettings, logger, localizer)
    {
    }

I want to return an actionresult from the global.asax with the following code:

IController controller = new HomeController(dependency should go here);

and I want unity to resolve the dependency (customer, siteSettings, logger, localizer) rather than I creating the dependencies on global.asax one more time and pass it into controller.

somecode like the following should work but I havent been able to get it sorted:

IController controller = UnityManager.Instance.Resolve(controllerType) as IController;
هل كانت مفيدة؟

المحلول 2

and here is how I finally solved it:

IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(HttpContext.Current.Request.RequestContext, "Home"); 
controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));

نصائح أخرى

You'd first have to configure your Unity DI container. The common practice is to create a bootstrapper, with a static method to handle the registrations, like:

public class ContainerBootstrapper {
    public static void RegisterTypes(IUnityContainer container) {
        container.RegisterType<ICustomer, CustomerImplementation>(/* configure your class implementation here */);
        container.RegisterType<ISiteSettings, SettingsImplementation>(...);
        container.RegisterType<ILogger, LoggerImplementation(...));
        ...

    }
}

and call it from your global.asax

var container = new UnityContainer();
ContainerBootstrap.RegisterTypes(container);

To resolve controller in an ASP.NET MVC4 application, you need to replace the standard Controller factory implementation. For more information check out Unity documentation on MSDN. There is a "Unity bootstrapper for ASP.NET MVC" nuget package available, which containers a standard UnityDependencyResolver implementation, you just need to register it with:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top