我正在尝试注册一个类型,它在其构造函数中将2个字符串作为参数。字符串是其他两种注册类型的属性。我尝试了以下操作,但注入IDatabaseManagement时参数为空,即使其他注入类型已解析并具有属性值:
container.RegisterType<IConnectionInfo, ConnectionInfo>()
.RegisterType<IUserInfo, UserInfo>()
.RegisterType<IDatabaseManagement, DatabaseManagement>(new InjectionConstructor(
container.Resolve<IConnectionInfo>().Connection
,
container.Resolve<IUserInfo>().CurrentUser.UserEmployeeNumber
));
我也尝试过一个ResolvedParameter,但是这会在演员阵容中爆炸:
container.RegisterType<IConnectionInfo, ConnectionInfo>()
.RegisterType<IUserInfo, UserInfo>()
.RegisterType<IDatabaseManagement, DatabaseManagement>(new InjectionConstructor(
((IConnectionInfo)(new ResolvedParameter<IConnectionInfo>())).Connection
,
((IUserInfo)(new ResolvedParameter<IUserInfo>())).CurrentUser.UserEmployeeNumber
));
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
最干净的答案是将DatabaseManagement
构造函数更改为IConnectionInfo
和IUserInfo
而不是两个字符串。
如果这是不可接受的,您可以使用InjectionFactory
代替。
container.RegisterType<IDatabaseManagement, DatabaseManagement>(
new InjectionFactory(c =>
{
var connectionInfo = c.Resolve<IConnectionInfo>();
var userInfo = c.Resolve<IUserInfo>();
return new DatabaseManagement(
connectionInfo.Connection,
userInfo.CurrentUser.UserEmployeeNumber);
}));
它在第一个示例中失败的原因是因为它在执行RegisterType调用时立即解析IConnectionInfo
和IUserInfo
的实例,并将这些单个实例用于{{1}的所有结果}。每次调用Resolve时都会执行IDatabaseManagement
。
答案 1 :(得分:0)
示例:
我有用于MSSQL的IDataContext和用于MySQL的另一个。
此示例使用命名类型解析。注意&#34; db&#34;命名解决。您必须将New InjectionConstructor传递给需要特定命名解析的每种类型。
container.RegisterType(Of IDataContextAsync, dbEntities)("db", New InjectionConstructor())
container.RegisterType(Of IUnitOfWorkAsync, UnitOfWork)("UnitOfWork", New InjectionConstructor(New ResolvedParameter(Of IDataContextAsync)("db")))
'Exceptions example
container.RegisterType(Of IRepositoryAsync(Of Exception), Repository(Of Exception))("iExceptionRepository",
New InjectionConstructor(New ResolvedParameter(Of IDataContextAsync)("db"),
New ResolvedParameter(Of IUnitOfWorkAsync)("UnitOfWork")))
&#39; sql容器
container.RegisterType(Of IDataContextAsync, DataMart)(New HierarchicalLifetimeManager)
container.RegisterType(Of IUnitOfWorkAsync, UnitOfWork)(New HierarchicalLifetimeManager)
'brands
container.RegisterType(Of IRepositoryAsync(Of Brand), Repository(Of Brand))