unity: 当前类型是接口,无法构造

Unity: The current type is an interface and cannot be constructed

开始使用以下代码

public interface IDataContextAsync : IDataContext
{
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
    Task<int> SaveChangesAsync();
}

public partial class DB1Context : DataContext{ }

public partial class DB2Context : DataContext{ }

下面是UnityConfig文件。注意:我正在为 ASP.Net MVC 使用 Nuget 引导程序,下面是我的 UnityConfig 文件

        public static void RegisterTypes(IUnityContainer container)
    {           
        container
            .RegisterType<IDataContextAsync, DB1Context>("DB1Context", new PerRequestLifetimeManager())
            //.RegisterType<IDataContextAsync, DB2Context>("DB2Context", new PerRequestLifetimeManager())
            .RegisterType<IRepositoryProvider, RepositoryProvider>(
                new PerRequestLifetimeManager(),
                new InjectionConstructor(new object[] {new RepositoryFactories()})
            )
            .
            .
            .
            .
    }

我遇到以下错误:

The current type, Repository.Pattern.DataContext.IDataContextAsync, is an interface and cannot be constructed. Are you missing a type mapping?

了解此命名实例不适用于我的 UnityConfig。 伙计们有什么想法吗?

提前致谢

您正在执行解析的服务定位器(在您的构造函数请求 IDataContextAsync 之后)可能正在尝试这样解析:

Current.Resolve<IDataContextAsync>()

需要这样解析的时候

Current.Resolve<IDataContextAsync>("DB1Context");

并且它不会内置任何额外的逻辑来让它知道这一点。

如果你想有条件地解决你可以使用注入工厂:

   public static class Factory
   {
        public static IDataContextAsync GetDataContext()
        {
            if (DateTime.Now.Hour > 10)
            {
                return new DB1Context();
            }
            else
            {
                return new DB2Context();
            }
        }
    }

..并像这样注册 IDataContextAsync:

Current.RegisterType<IDataContextAsync>(new InjectionFactory(c => Factory.GetDataContext()));

因为它需要一个委托,所以你不一定需要静态 class / 方法,可以内联。