views:

142

answers:

2

I've recently had to update a relatively large control library that uses Ninject 1.0 to Ninject 2.0 to help resolve some issues I had with 1.0. The update has gone well and I think Ninject 2.0 is a lot quicker.

However to try and avoid this problem in the future I have created my own interface for injecting fields and properties (which will essentially call methods on the IOC container I wish to use within the current web application). So now my control library is independant of any particular IOC container which will speed up any changes in that area in the future.

I was wondering has anyone else has done the same thing?

I'm happy with what it has achieved but ideally I would like to update it. In my controls I create these injected fields often as protected and set them in the constructor for that control.

IBlogService _blogService = null;
IEmailService _emailService = null;

public Templates_BlogTemplate()
{
    Inject(ref _blogService);
    Inject(ref _emailService);
}

The problem I have with the above is that I have to use "ref" on all objects to actually set the property and I cannot use that on properties directly.

I would prefer to do something along these lines but I don't think it is possible.

IBlogService _blogService = null;
IEmailService _emailService = null;

public Templates_BlogTemplate()
{
    Inject(_blogService, _emailService);
}

Has anyone got any ideas of how to neaten the code up or make it work in a cleaner way? I also would want to avoid attributes so it forces the developer to make a decision to inject the variable at a certain point within the control.

All thoughts and feelings are welcome.

Thanks

+1  A: 

Support property injection, and inject dependencies to "this".

In my case, I have a base class that calls StructureMap.BuildUp(this), and the user control would have properties like:

public IBlogService _blogService{get;set;}
public IEmailService _emailService{get;set;}

The only line specific to structuremap I have is in the base class. If ninject allows you to do this, then you can call your code handing it the control instance, and let it inject the properties based on its configuration.

eglasius
+1  A: 

You may want to look at IServiceLocator as described by Glenn Block

It's a shared interface that can be used to take advantage of IoC without taking a hard dependency on the container.

Graeme Bradbury