简体   繁体   English

结构图和泛型类型

[英]Structuremap and generic types

I have a situation which seems a bit different from others I've seen. 我的情况与我见过的其他情况有点不同。 For clarrification, this isn't the normal question eg; 为了澄清,这不是正常的问题,例如; something like IAClass maps to AClass etc - that involves using basically a single concrete classes per interface. 类似于IAClass映射到AClass等 - 这涉及到每个接口基本上使用单个具体类。

This involves having a single generic class, but I want to be able to load ALL possible usages of it. 这涉及到一个通用类,但我希望能够加载它的所有可能用法。

Eg - the main class is of 例如 - 主要类是

public class MyClass<TDomainObject> : IMyClass<TDomainObject> 
     where TDomainObject : DomainObject

So example usages would be 所以示例用法是

IMyClass<Person> p = new MyClass<Person>;
IMyClass<Employer> p = new MyClass<Employer>;

Ie for all DomainObjects I would like to be able to load a MyClass<> for. 即对于所有DomainObjects,我希望能够加载MyClass <>。 So you can see I don't use a specific class for each declaration, they all use the same one. 所以你可以看到我没有为每个声明使用特定的类,它们都使用相同的类。

How would I get this loaded into StructureMap? 我如何将其加载到StructureMap中?

That's actually the more straightforward use of generics. 这实际上是对泛型的更直接的使用。

For(typeof(IMyClass<>)).Use(typeof(MyClass<>))

If you are using an older version of Structuremap, substitute the more verbose ForRequestType and TheDefaultIsConcreteType . 如果您使用的是旧版本的Structuremap,请使用更详细的ForRequestTypeTheDefaultIsConcreteType

After some searching, I found out that you can use the auto register feature on Structuremap 2.5+ with generics over conventions, just like you could do with non-generics. 经过一些搜索,我发现你可以使用Structuremap 2.5+上的自动注册功能,使用泛型而不是泛型,就像你可以使用非泛型一样。

Just create your container like: 只需创建您的容器:

return new Container(x =>
        {
            x.Scan(y =>
            {
                y.TheCallingAssembly();
                y.AddAllTypesOf(typeof(IMyClass<>));
                y.WithDefaultConventions();
            });
        });

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

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