Auto Register Generic Types

68 views
Skip to first unread message

Robin Clowers

unread,
Aug 1, 2008, 5:23:13 PM8/1/08
to structuremap-users
I'm wondering if there is an easy way to have all my Repository<T>'s
be registered as concrete types for IRepository<T>? So for instance
when I resolve IRepository<User> I get Repository<User>.

Chad Myers

unread,
Aug 1, 2008, 5:40:09 PM8/1/08
to structure...@googlegroups.com
StructureMapConfiguration
.ForRequestedType<IRepository<>>()
.TheDefaultIsConcreteType<Repository<>>();

... later....

IRepository<Foo> repo = ObjectFactory.GetInstance<IRepository<Foo>>();

-c

Robin Clowers

unread,
Aug 1, 2008, 5:55:04 PM8/1/08
to structuremap-users
Thanks Chad; that syntax does not seem to work (don't you have to
specify the type arg in that usage?) but this works for the situation
I described:

StructureMapConfiguration
.ForRequestedType(typeof (IRepository<>))
.TheDefaultIsConcreteType(typeof (Repository<>));

Unfortunately I oversimplified my situation... Repository<T> is
actually an abstract base class, I need IRepository<User> to resolve
to UserRepository (which inherits IRepository<User>). How can I
handle this?

Chad Myers

unread,
Aug 1, 2008, 6:48:59 PM8/1/08
to structure...@googlegroups.com
Robin,

You're right. Sorry about that. I typed that out from memory and apparently
it's not so good anymore.

Jeremy may correct me on this one, but I don't think there any way to do
what you're proposing using the ForRequestedType() syntax without specifying
them all manually.

What you've got there is a convention for your repositories, so you might
consider using a convention scanner (ITypeScanner in StructureMap parlance).

The code is too much for email, so I've linked it here:

http://www.pastie.org/245960

Robin Clowers

unread,
Aug 1, 2008, 7:04:35 PM8/1/08
to structuremap-users
Chad, that convention scanner works great, you practically do my job
for me! I really appreciate your help.

Robin

Chad Myers

unread,
Aug 1, 2008, 7:09:00 PM8/1/08
to structure...@googlegroups.com
Well, I had some ulterior motives :)

Full disclosure: I've been meaning to do a blog post for that same type of
thing and so I plan on using that code (or some form of it) in my blog post.
Reply all
Reply to author
Forward
0 new messages