如何使用 StructureMap 对类型进行分组?
我有一些类
public interface IProvider
{
void Load(int id);
}
public class Provider1 : IProvider
{
public void Load(int id) {}
}
public class Provider2 : IProvider
{
public void Load(int id) {}
}
public interface IService
{
void Load(int id);
}
public class Service : IService
{
IProvider provider;
public Service(IProvider provider) { this.provider=provider; }
public void Load(int id) { provider.Load(id); }
}
,并且我像这样使用 StructureMap 注册了它们:
For<IService>().Use<Service>().Named("core");
For<IProvider>().Use<Provider1>().Named("core");
For<IService>().Use<Service>().Named("gen");
For<IProvider>().Use<Provider2>().Named("gen");
但是当我尝试通过
var service1 = ObjectFactory.GetNamedInstance<IService>("core");
var service2 = ObjectFactory.GetNamedInstance<IService>("gen");
在这两种情况下 IProvider 实例化到 Provider2 来获取服务时,为什么?
我预计第一种情况 IProvider 将实例化到 Provider1 对于 Provider2 的第二种情况
那么,我需要如何注册它们才能获得我想要的东西?
I have some classes
public interface IProvider
{
void Load(int id);
}
public class Provider1 : IProvider
{
public void Load(int id) {}
}
public class Provider2 : IProvider
{
public void Load(int id) {}
}
public interface IService
{
void Load(int id);
}
public class Service : IService
{
IProvider provider;
public Service(IProvider provider) { this.provider=provider; }
public void Load(int id) { provider.Load(id); }
}
and I registered them with StructureMap like this:
For<IService>().Use<Service>().Named("core");
For<IProvider>().Use<Provider1>().Named("core");
For<IService>().Use<Service>().Named("gen");
For<IProvider>().Use<Provider2>().Named("gen");
but when I try to get Service by
var service1 = ObjectFactory.GetNamedInstance<IService>("core");
var service2 = ObjectFactory.GetNamedInstance<IService>("gen");
so in both cases IProvider instanciated to Provider2, why?
I expected for 1st case the IProvider will instanciate to Provider1
and for 2nd case to Provider2
So, how I need to register them in order to get what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有告诉结构图服务的不同实例具有哪些依赖关系。为了说明这一点,请使用 Ctor 方法指示创建实例时应传递哪些参数。
请注意使用“添加”而不是“使用”。 add 表示我们正在添加一个新实例,use 表示该实例应该是默认的。因此,如果您希望能够将核心设置为默认值,您可以按如下方式注册:
并解析如下实例:
You're not telling structuremap what dependencies the different instances of Service are having. In order to tell, use the Ctor method that indicate what arguments should be passed when creating an instance.
Note the use of Add instead of Use. The add indicates that we are adding a new instance, use indicates that a instance should be default. So if you want to be able to have core as default you can register as follows:
and resolve the instances like this:
您可以尝试告诉结构映射您想要 service1 的 IProvider 实例,名称如下:
You can try telling structuremap what instance of IProvider you want for service1 with the name like this: