配置 Unity 以使用 Web api

Configure Unity to work with Web api

Unity 配置新手,我正在尝试在我的项目中实现它。但是,我被卡住了。

我收到以下错误:当前类型 System.Web.Mvc.IControllerFactory 是一个接口,无法构造。您是否缺少类型映射?

容器类

public class ContainerBootstrapper
    {
        public static void ConfigureUnityContainer()
        {
            //simple registeration
            container.RegisterType<IProduct, ProductHelper>(); //maps interface to a concrete type

            System.Web.Mvc.DependencyResolver.SetResolver(new MyProjectControllerDependency(container));

        }

    }

DependencyResolver

public class MyProjectControllerDependency : IDependencyResolver
{
private IUnityContainer _container;

public MyProjectControllerDependency(IUnityContainer container)
{
    this._container = container;
}

public object GetService(Type serviceType)
{
    return _container.Resolve(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
    return _container.ResolveAll(serviceType);
}

控制器:

public class ProductController : ApiController
{
    private readonly IProduct _iproduct;

    public ProductController(IProduct product)
    {
        this._iproduct = product;
    }
 //controller methods
}

界面

public interface IProduct
{
    List<ProductViewModel> GetProductByBarcode(string value);
    string GetProductPrice(string value);
}

帮手

public class ProductHelper : IProduct
    {
        //private readonly IProduct _iproduct;

        //public ProductHelper(IProduct iproduct)
        //{
        //    this._iproduct = iproduct;
        //}

        public List<ProductViewModel> GetProductByBarcode(string value)
        {
            throw new NotImplementedException();
        }

        public string GetProductPrice(string value)
        {
            throw new NotImplementedException();
        }
}

我不明白,我错过了什么?谁能指出我正确的方向。

对于 ASP.NET MVC 和 WebApi 项目,仅使用 Unity 是不够的。对于这些项目,您还需要从 nuget 安装 Unity.MVC

这是开箱即用的 classes。您只需要在 UnityContainer 中注册依赖项即可完成。

安装 Unity.MVC 后,它会创建 classes UnityMvcActivatorUnityConfigUnityConfig class 有初始化UnityContainer的实现。您需要做的就是在 RegisterTypes 方法中注册依赖项。

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<IBaseClass, BaseClass>(); // Registering types
    container.LoadConfiguration();
}

您不需要创建任何自定义类型或实现,除非您有完全不同的要求。

这应该可以帮助您解决问题。