问题描述
从下面的代码开始
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文件
Below is the UnityConfig file. Note: I am using Nuget bootstrapper for ASP.Net MVC and below is my UnityConfig file
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()})
)
.
.
.
.
}
我得到以下错误:
了解此命名实例不适用于我的UnityConfig.有想法的人吗?
Understand that this named instances is not working with my UnityConfig.Any idea guys?
预先感谢
推荐答案
正在执行解析的服务定位器(在构造函数要求IDataContextAsync之后)可能正在尝试这样解决:
Your service locator that is doing the resolving (after your constructor asks for IDataContextAsync) is probably trying to resolve like this:
Current.Resolve<IDataContextAsync>()
何时需要这样解决
Current.Resolve<IDataContextAsync>("DB1Context");
而且它不会内置任何额外的逻辑.
and there wouldn't be any extra logic built into it for it to know that.
如果要有条件解决,可以使用注射工厂:
If you want to conditionally resolve you could use an injection factory:
public static class Factory
{
public static IDataContextAsync GetDataContext()
{
if (DateTime.Now.Hour > 10)
{
return new DB1Context();
}
else
{
return new DB2Context();
}
}
}
..并像这样注册IDataContextAsync:
..and register IDataContextAsync like this:
Current.RegisterType<IDataContextAsync>(new InjectionFactory(c => Factory.GetDataContext()));
由于需要委托,因此您不一定需要静态类/方法,而是可以内联地完成它.
Since it takes a delegate you don't necessarily need the static class / method and could do it inline.
这篇关于Unity:当前类型是接口,无法构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!