views:

235

answers:

1

I have been searching for a while.

I'm not new to dependency injection and have used StructureMap with several projects MVC and the like, but I felt like giving Ninject a go, so as not to miss out on the fun.

I am trying to use Ninject with an existing web app which I am bringing up-to-date.

I couldn't find on the blogs and wiki provided by Ninject, I am a little impatient to be honest so may have missed it, and the first few pages of google appear to be out of date or talking about using MVC with Ninject.

So far I have the following and it works, but I was hoping someone could point out a less intrusive option, regarding calling the ServiceModule to the Kernel and injecting a property with the desired bind from the web app.

What I have so far is a ServiceModule:

public class ServiceModule : NinjectModule
{
    public override void Load()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        Bind<IPreRegistrationService>().To<PreRegistrationService>()
            .WithConstructorArgument("connectionString",connectionString);
    }
}

Then in my page I have defined a private variable:

private IPreRegistrationService xfemPreRegistrationService = null;

Then in the page load event:

    IKernel kernel = new StandardKernel(new ServiceModule());
    xfemPreRegistrationService = kernel.Get<IPreRegistrationService>();

So this works, but what I would like is to move on to a phase where all I define is:

[Inject]
public IPreRegistrationService xfemPreRegistrationService { get; set; }

on a page and the rest is magic.

Cheers

+1  A: 

Thanks to this stackoverflow post I found out about the extension Ninject.Web

Problem I found was you need to start off using Ninject.Web and I could not as I already have a PageBase defined to handle securities and the such.

So, the only way I could see was to take the KernelContainer class from the project (as KernelContainer is defined as internal):

Then call from the global asax OnApplicationStart:

KernelContainer.Kernel = new StandardKernel(new ServiceModule());

// Request injections for the application itself.
KernelContainer.Inject(this);

Then in my PageBase from the OnInit method:

KernelContainer.Inject(this);

This has allowed me to reach my target of simply putting:

[Inject]
public IPreRegistrationService xfemPreRegistrationService { get; set; }

where needed

Luke Duddridge