Unity没有解决我的课程

时间:2014-08-15 11:57:52

标签: c# asp.net-web-api dependency-injection unity-container unit-of-work

我在解决方案中有更多项目(主要是类库和一个WebAPI项目),我在Common项目中解决了这个项目中的依赖项问题。以下是我如何设置依赖

的示例
    [Dependency]
    public IDbContextFactory DbContextFactory
    {
        get { return _factory; }
        set
        {
            _factory = value;
            DbContext = _factory.Create();
        }
    }
    [Dependency]
    public IUnitOfWorkManager Manager
    {
        get { return _manager; }
        set
        {
            _manager = value;
            _manager.AddOpenUnitOfWork(this);
        }
    }

在同一个项目中,我通过这个类将注册接口和类安装到Unity容器中

public class CommonUnityConfiguration : IUnityConfiguration
{
    public void Configurate(UnityContainer container)
    {
        container
            .RegisterType<IUnitOfWorkManager, UnitOfWorkManager>()
            .RegisterType<IDbContextFactory, DbContextFactory>();
    }
}

最后在WebAPI中我有WebApiConfiguration,我正在创建Unity容器并注册所有类。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Create instance for Unity container - let's try to run!
        var container = new UnityContainer();
        container.RegisterType<IUserRepository, UserRepository>(new HierarchicalLifetimeManager());
        config.DependencyResolver = new UnityResolver(container);
        // Add project classes to IoC container
        new CommonUnityConfiguration().Configurate(container);

        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

问题是,IDbContextFactory属性和IUnitOfWorkManager未解析。你有什么建议吗,我应该检查什么?

1 个答案:

答案 0 :(得分:0)

我认为您需要切换这两行:

config.DependencyResolver = new UnityResolver(container);

new CommonUnityConfiguration().Configurate(container);

在CommonUnityConfiguration类中完全配置它之前,您已将DependencyResolver设置为UnityREsolver