Registering MicroLite with Ninject

If you are using MicroLite in an application and using Ninject as your IOC container, it is extremely easy to configure Ninject to resolve an ISession as a dependency.

In your application startup, where you are registering types in the kernel, simply add the 2 bindings below:

var sessionFactory = Configure
    .Fluently()
    .ForConnection("Northwind")
    .CreateSessionFactory();

var kernel = new StandardKernel();
kernel.Bind<ISessionFactory>().ToConstant(sessionFactory);
kernel.Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<ISessionFactory>().OpenSession());

If you use the default binding scope of transient, your class should take ownership of the ISession and dispose of it when the class has finished using it.

If you add the Ninject Named Scope extension, you can bind the ISession with .InParentScope(). In this case, Ninject will dispose of the ISession when the parent object is garbage collected so you don’t have to dispose of it yourself.

It should be just as simple to register MicroLite with any other IOC container (Autofac, Unity, Windsor etc).

This article was written for version 1.2.2 of the MicroLite framework.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s