[英]Registering a Contrete Class which has a Generic Type with StructureMap
I am new to StructureMap and have the following issue which seems to be the reverse of issues other people are having. 我是StructureMap的新手,并且有以下问题,这似乎与其他人遇到的问题相反。 I have a generic
UnitOfWorkClass
defined as follows: 我有一个通用的
UnitOfWorkClass
定义如下:
public class UnitOfWork<TContext> : IUnitOfWork
where TContext : IContext, new()
{
....
}
However I'm baffled about how you'd register this to resolve if I've got several different possibilities for the concrete instance. 但是,如果我为具体实例提供了几种不同的可能性,我会对你如何注册这个问题感到困惑。
I've seen plenty of examples where people have a generic interface such as: 我见过很多人都有通用界面的例子,例如:
StructureMap Auto registration for generic types using Scan StructureMap使用“扫描”自动注册泛型类型
So I guess the question could be asked if I need to re-look at my design too! 所以我想问我是否需要重新审视我的设计问题!
Thanks a lot! 非常感谢!
So I have a class which takes two parameters into the constructor: 所以我有一个类,它将两个参数带入构造函数:
ObjectFactory.Initialize(cfg =>
{
var firstContext = cfg.For<IContext>().Use<MyFirstContext>();
var secondContext = cfg.For<IContext>().Use<MySecondContext>();
var firstUnitOfWork =
cfg.For<IUnitOfWork>().Use<UnitOfWork<MyFirstContext>>()
.Ctor<IContext>().Is(firstContext);
var secondUnitOfWork =
cfg.For<IUnitOfWork>().Use<UnitOfWork<MySecondContext>>()
.Ctor<IContext>().Is(secondContext);
cfg.For<IMyClass>().Use<MySecondContext>()
.Ctor<IUnitOfWork>("firstConstructor").Is(firstUnitOfWork)
.Ctor<IUnitOfWork>("secondConstructor").Is(secondUnitOfWork);
});
Then as my object graph gets built I do the following: 然后,当我的对象图构建时,我执行以下操作:
ObjectFactory.Initialize(cfg => { var firstContext = cfg.For<IContext>().Use<MyFirstContext>(); var secondContext = cfg.For<IContext>().Use<MySecondContext>(); var firstUnitOfWork = cfg.For<IUnitOfWork>().Use<UnitOfWork<MyFirstContext>>() .Ctor<IContext>().Is(firstContext); var secondUnitOfWork = cfg.For<IUnitOfWork>().Use<UnitOfWork<MySecondContext>>() .Ctor<IContext>().Is(secondContext); cfg.For<IMyClass>().Use<MySecondContext>() .Ctor<IUnitOfWork>("firstConstructor").Is(firstUnitOfWork) .Ctor<IUnitOfWork>("secondConstructor").Is(secondUnitOfWork); });
So what I've done here is: 所以我在这里做的是:
It doesn't feel perfect but I think this suits my needs... 它感觉不完美,但我认为这符合我的需求......
I'm not entirely sure I understand what you want, but if you made the interface generic as in IUnitOfWork then you can register like this: 我不完全确定我理解你想要什么,但是如果你像IUnitOfWork那样使接口通用,那么你可以像这样注册:
ObjectFactory.Initialize(x =>
{
x.For(typeof(IUnitOfWork<>)).Use(typeof(UnitOfWork<>));
}
and StructureMap will supply the implementing class with the correct type. 和StructureMap将为实现类提供正确的类型。 Does that give you waht you need?
那会给你带来什么吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.