Невозможно внедрить зависимости в Контроллер веб-API ASP.NET с использованием Unity

Удалось ли кому-нибудь запустить контейнер IoC для внедрения зависимостей в контроллеры ASP.NET WebAPI? Кажется, я не могу заставить его работать.

Вот чем я сейчас занимаюсь.

В моем global.ascx.cs:

    public static void RegisterRoutes(RouteCollection routes)
    {
            // code intentionally omitted 
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        IUnityContainer container = BuildUnityContainer();

        System.Web.Http.GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            t =>
            {
                try
                {
                    return container.Resolve(t);
                }
                catch (ResolutionFailedException)
                {
                    return null;
                }
            },
            t =>
            {
                try
                {
                    return container.ResolveAll(t);
                }
                catch (ResolutionFailedException)
                {
                    return new System.Collections.Generic.List<object>();
                }
            });

        System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container)); 

        BundleTable.Bundles.RegisterTemplateBundles();
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer().LoadConfiguration();

        return container;
    }

Моя фабрика контроллеров:

public class UnityControllerFactory : DefaultControllerFactory
            {
                private IUnityContainer _container;

                public UnityControllerFactory(IUnityContainer container)
                {
                    _container = container;
                }

                public override IController CreateController(System.Web.Routing.RequestContext requestContext,
                                                    string controllerName)
                {
                    Type controllerType = base.GetControllerType(requestContext, controllerName);

                    return (IController)_container.Resolve(controllerType);
                }
            }

Похоже, что мой файл юнити никогда не ищет разрешения зависимостей, и я получаю сообщение об ошибке, например:

Произошла ошибка при попытке создать контроллер типа 'PersonalShopper.Services.WebApi.Controllers.ShoppingListController'. Убедитесь, что у контроллера есть публичный конструктор без параметров.

в System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext КонтроллерКонтекст, ТипКонтроллерТип) в System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateInstance(HttpControllerContext controllerContext, HttpControllerDescriptorcontrollerDescriptor) в System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateController(HttpControllerContext controllerContext, String имя_контроллера) в System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal (HttpRequestMessage запрос, CancellationToken, CancellationToken) в System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancelToken)

Контроллер выглядит так:

public class ShoppingListController : System.Web.Http.ApiController
    {
        private Repositories.IProductListRepository _ProductListRepository;


        public ShoppingListController(Repositories.IUserRepository userRepository,
            Repositories.IProductListRepository productListRepository)
        {
            _ProductListRepository = productListRepository;
        }
}

Мой файл единства выглядит так:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="PersonalShopper.Repositories.IProductListRepository, PersonalShopper.Repositories" mapTo="PersonalShopper.Implementations.MongoRepositories.ProductListRepository, PersonalShopper.Implementations" />
  </container>
</unity>

Обратите внимание, что у меня нет регистрации для самого контроллера, потому что в предыдущих версиях mvc фабрика контроллеров выясняла, что зависимости должны быть разрешены.

Похоже, моя фабрика контроллеров никогда не вызывается.

81
задан Jim Aho 11 September 2015 в 13:20
поделиться