我们正在从StructureMap迁移到Lamar,但找不到在运行时传递参数的“ Lamar版本”。
我们有一个需要字符串参数(伪代码)的类:
public class MyRepository {
public MyRepository(string accountId) {}
}
Run Code Online (Sandbox Code Playgroud)
…还有一家工厂
public class MyRepoFactory(Container container) {
public MyRepository GetRepositoryForAccount(string accountId) =>
container
// With() is not available in Lamar?
.With("accountId").EqualTo(accountId)
.GetInstance<IMyRepository>();
}
Run Code Online (Sandbox Code Playgroud)
实际上,还有其他依赖项。
怎么说Lamar GetInstance()可以IMyRepository使用值xy作为名为的构造函数参数accountId?
我认为拉马尔有两种方法。
使用属性
虽然 Lamar 没有提供With(),但解决方法可能是使帐户成为您在工厂方法中设置的属性,或者让工厂简单地从容器中手动获取所有存储库的依赖项。毕竟,它是一家工厂,因此从设计的角度来看,将其与其生产的类型紧密联系起来似乎很好。
使用上下文
更好的方法可能是在上下文中设置 accountId 并使用存储库中的上下文:
public class ExecutionContext
{
public Guid AccountId { get; set; } = Guid.NewGuid();
}
Run Code Online (Sandbox Code Playgroud)
存储库看起来像这样
public class MyRepository
{
public ExecutionContext Context { get; }
public MyRepository(ExecutionContext context)
{
Context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
使上下文可注入...
var container = new Container(_ =>
{
_.Injectable<ExecutionContext>();
});
Run Code Online (Sandbox Code Playgroud)
然后,在你的工厂...
public MyRepository GetRepositoryForAccount(string accountId) {
var nested = container.GetNestedContainer();
var context = new ExecutionContext{ AccountId = accountId };
nested.Inject(context);
return nested.GetInstance<IMyRepository>()
}
Run Code Online (Sandbox Code Playgroud)
文档:https://jasperfx.github.io/lamar/documentation/ioc/injecting-at-runtime/
您可能还需要考虑在这种情况下是否真的需要工厂,或者直接使用嵌套的可注入容器是否可以实现更简洁的设计。
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |