views:

113

answers:

1

So I'm starting to use Ninject for dependency injection and I'm wondering what people think of using a kernel as an object factory for Unit of Work type objects like Linq2Sql Datacontexts. I would just inject them like normal dependencies, but this introduces some object lifetime issues I'd like to avoid. DataContexts are different than general dependencies because you're supposed to spin up new instances as needed and dispose of them when you're done.

To do something like this I'd simply setup a provider like so...

class SomeDataContextProvider : Provider<SomeDataContext>
{
    private static string _connectionString = "someConnectionString"
    protected override SomeDataContext CreateInstance(IContext context)
    {
        return new SomeDataContext(_connectionString);
    }
}

Bind them in a module...

class MyModule : Ninject.Modules.NinjectModule
{
    public override void Load()
    {
        Bind<SomeDataContext>().ToProvider(SomeDataContextProvider);
    }
}

And use the standard kernel when needed...

class MyClassThatNeedsADataContext
{
    private StandardKernel _kernel = new StandardKernel(new MyModule());

    public void SomeMethod()
    {
        using (var db = _kernel.Get<SomeDataContext>())
        {
            //Use the context
        }
    }
}

It seems a little heavy for what is essentially a static factory but I'm using Ninject for other stuff anyway. I like that it gives members on the team a convention for factories instead of just letting them wing it (creating a bunch of different factory classes in weird places, or just putting static methods on the objects etc).

Thoughts? Is there a better way to deal with Unit of work dependencies like DataContexts or WCF Service Clients using dependency injection?

+3  A: 

I don't like injecting containers into classes since it creates a dependency between your application and the container, and makes it less clear what dependencies a class has. I don't really see how this approach gains you anything over a factory, so personally I'd create a 'DataContextFactory' and inject that into any classes that need to access the database.

Lee
Much Better. Somewhere my brain got caught between injecting the dependency and injecting the factory. Thanks.
Jason Punyon