提问人:tRuEsAtM 提问时间:8/25/2022 最后编辑:SteventRuEsAtM 更新时间:8/26/2022 访问量:397
Microsoft DI相当于Castle.Windsor的DependsOn Dependency.OnValue
What's the Microsoft DI equivalent of Castle.Windsor's DependsOn Dependency.OnValue
问:
我有一个 .NET Standard 2.0 库,它按以下方式设置了 DI,
container.Register(Component.For<IMyFactory>()
.ImplementedBy<MyFactory>()
.DependsOn(Dependency.OnValue("connectionString",
container.Resolve<IDataAccess>().ConnectionString))
.LifestyleSingleton());
container.Register(Component.For<IMyAdapter>()
.ImplementedBy<MyAdapter>().LifestyleTransient());
这些语句的等价物是什么?Microsoft.Extensions.DependencyInjection
我想摆脱依赖关系。Castle.Windsor
答:
1赞
Steven
8/25/2022
#1
services.AddSingleton<IMyFactory>(sp =>
ActivatorUtilities.CreateInstance<MyFactory>(
sp,
sp.GetRequiredService<IDataAccess>().ConnectionString));
services.AddTransient<IMyAdapter, MyAdapter>();
评论
0赞
tRuEsAtM
8/25/2022
对于第一个,我在最后一行收到一个错误,说参数 2 无法从 转换为sp.GetRequiredService<IDataAccess>().ConnectionString));
string
System.Type
1赞
Jeremy Lakeman
8/25/2022
我建议您更改构造函数以采用参数。使用复杂类型描述所有依赖项要容易得多,而不需要工厂方法。MyFactory
IDataAccess
0赞
Steven
8/25/2022
@tRuEsAtM:我的回答有误。我更新了我的答案。请注意,我确实同意 Jeremy 关于注射的观点。事实上,您的 IS 运行时数据似乎。应防止将运行时数据注入组件。最好是仅在开始使用 .IDataAccess
ConnectionString
IDataAccess
ConnectionString
MyFactory
评论
Services.AddTransient
和瞬态和单例Services.AddSingleton