views:

64

answers:

1

We've begun using Dependency Injection recently, and we've chosen Ninject 2 (for now) as our IoC Container. As I refactor our solution to incorporate DI principles, I've run into something that bugs me a little, and I'm wondering if there's an easy way to get around it.

For our data layer, we have a whole bunch of data-access classes that inherit the same generic class (EntityMapper). While in the past we've always constructed a new instance of these classes when we needed one, they really could all be changed into Singletons. We've overridden ObjectDataSource to use Ninject to instantiate its data-access object, so any time we create an ObjectDataSource that points to one of our EntityMapper classes, Ninject will use its default self-binding strategy to inject the necessary dependencies. Since there are so many of these classes, we'd rather not have to create an explicit binding for each of our EntityMapper classes, and we'd rather not have to put a special attribute on every one of them either. However, I would like to be able to instruct Ninject to make any instance of EntityMapper into a singleton class. Something like this:

Bind(t => typeof(IEntityMapper).IsAssignableFrom(t)).InSingletonScope();

Is there any way to do this?

A: 

You can use the conventions extension to do the following

var kernel = new StandardKernel();
kernel.Scan( x=>
             {
                 x.FromAssemblyContaining<MyEntityMapper>();
                 x.FromCallingAssembly();
                 x.WhereTypeInheritsFrom<IEntityMapper>();
                 x.InSingletonScope();
             } );
Ian Davis