简体   繁体   English

基于派生类型的StructureMap开放泛型使用

[英]StructureMap Open Generics Use Based on Derived Type

I have two entity base classes: 我有两个实体基类:

public abstract class EntityBase { }
public abstract class ClientSpecificEntityBase : EntityBase

and two categories of entities: 和两类实体:

public class Thing : EntityBase { }
public class ClientSpecificThing : ClientSpecificEntityBase { }

and two types of services, which both implement IService<T> 和两种类型的服务,都实现了IService<T>

ServiceBase<T> : Service<T> where T : EntityBase
ClientSpecificServiceBase<T> : ServiceBase<T> where T : ClientSpecificEntityBase 

I'm using the following code to configure StructureMap: 我正在使用以下代码来配置StructureMap:

_.For(typeof(IService<>)).Use(typeof(ServiceBase<>));
_.For<IService<ClientSpecificEntityBase>>().Use<ClientSpecificServiceBase<ClientSpecificEntityBase>>();

But everytime I try to access IService<ClientSpecificThing> : 但是每次我尝试访问IService<ClientSpecificThing>

public ClientSpecificThingController(IService<ClientSpecificThing> service)

I am getting ServiceBase<ClientSpecificThing> rather than ClientSpecificServiceBase<ClientSpecificThing> 我正在获取ServiceBase<ClientSpecificThing>而不是ClientSpecificServiceBase<ClientSpecificThing>

Is there any way to get StructureMap to include the derived types when it maps ClientSpecificServiceBase<T> ? 有什么方法可以让StructureMap在映射ClientSpecificServiceBase<T>时包括派生类型?

No, you can't do what you're trying to do. 不,你不能做你想做的事。 The container isn't going to look through the registered components for base classes of generic types. 容器不会通过注册的组件查看泛型类型的基类。

This becomes more apparent if you remove the first registration, leaving only 如果您删除第一个注册,而仅留下,则这一点变得更加明显

_.For<IService<ClientSpecificEntityBase>>()
    .Use<ClientSpecificServiceBase<ClientSpecificEntityBase>>();

Now, if you call 现在,如果你打电话

var resolved = container.GetInstance<IService<ClientSpecificThing>>();

You'll get an exception: 您会得到一个例外:

StructureMap.StructureMapConfigurationException: No default Instance is registered and cannot be automatically determined for type 'IService' StructureMap.StructureMapConfigurationException:没有注册默认实例,并且无法自动确定类型'IService'的实例

So it's not that StructureMap is confused between the two registrations and is returning the wrong one. 因此,并不是将StructureMap混淆在两个注册之间并返回错误的注册。 It doesn't recognize that when you register this: 当您注册时,它不识别:

IService<ClientSpecificEntityBase>

that it can use that fulfill this because one generic type inherits from the other. 它可以使用来实现这一点,因为一个泛型类型是从另一个继承的。

IService<ClientSpecificThing>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM