2
votes

So, I am doing .NET MVC 3 based application and using Castle Windsor as an IOC container.

I am using it without any problems and working perfectly fine. Now I encountered this situation where I created an HTML helper which is exposing a method

public static string GetContentByKey(string key)
{
     //I need to use a service that is resolved by Windsor here
}

The problem is that in this Helper class I need to use a service that initialized through windsor, but since this helper is a static method there you have no option of constructor injection.

1
That kind of problem indicates that you are trying to use the wrong approach. Maybe you should take a step back and reconsider what you are trying to do.Sebastian Weber
I agree with Sebastian. If a class needs dependencies, it is probably more than just a 'helper' class. Design it just like you do with the rest of your services. In other words: don't make it static and define a single public constructor that takes all its dependencies.Steven

1 Answers

2
votes

I agree with the comments that you may have a design flaw.

That being said, if you have to do it there are a couple of ways you can go about it:

1) Use service locator: resolve the required interface implementation from within the method. Some regard this as an anti-pattern and it is a bit of a code smell.

2) Use a class-level static field that can be initialized (possibly starting with a null object implementation):

public static class MyHelper
{
    private static IMyService service = new NullMyService();

    public static void Assign(IMyService instance)
    {
        service = instance;
    }

    public static string DoSomething(this HtmlHelper html)
    {
        return service.Whatever();
    }
}

Then from your composition root (as is the favoured term nowadays) you set the service by calling the assign method:

...
MyHelper.Assign(container.Resolve<IMyService>());
...

May not feel 100% comfortable but will yield the desired result.