Dependency injection for extension classes?

Leonard picture Leonard · Mar 8, 2016 · Viewed 8.7k times · Source

I'm using Microsoft Unity as my IoC container. I have a number of extension classes which adds useful methods to my business objects This is the sort of code I use today:

public static class BusinessObjectExtensions
{
    public static bool CanDoStuff(this BusinessObject obj) 
    {
        var repository = BusinessHost.Resolver.Resolve<IRepository>();
        var args = new EArgument { Name = obj.Name };
        return repository.AMethod(obj.UserName, args);
    }
}

Is there a better way to manage dependency injection for extension classes?

Answer

mnwsmit picture mnwsmit · Mar 8, 2016

The de facto default way of Dependency Injection by Constructor Injection is not possible for static classes. It would be possible to use Parameter Injection like below, however that is not a very clean way.

public static class BusinessObjectExtensions
{
    public static bool CanDoStuff(this BusinessObject obj, IRepository repository)
    {
        var args = new EArgument { Name = obj.Name };
        return repository.AMethod(obj.UserName, args);
    }
}