Structuremap and generic types
Asked Answered
C

2

4

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.

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>;

I.e. for all DomainObjects I would like to be able to load a MyClass<> for. 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?

Convalescence answered 15/4, 2010 at 11:53 Comment(0)
M
3

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.

Mountaineering answered 15/4, 2010 at 12:36 Comment(1)
That's a really useful tip. I had no clue StructureMap could handle generics this way.Maurist
I
0

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.

Just create your container like:

return new Container(x =>
        {
            x.Scan(y =>
            {
                y.TheCallingAssembly();
                y.AddAllTypesOf(typeof(IMyClass<>));
                y.WithDefaultConventions();
            });
        });
Igenia answered 7/12, 2011 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.