Jake Petroules
Jake Petroules

Reputation: 24190

Dependency injection with UrlHelper

I am using Ninject in my web application, and as part of this I need some injections to be made in a UrlHelper extension method that resides in a separate assembly. I can't even get a static reference to the kernel because obviously the library assembly can't (nor should be) referring to my web application. I know static classes don't work well with DI, but because I need to use UrlHelper it makes things a little more complicated. How could I rearchitect this? Let me know if you need to see any code or need more information.

Upvotes: 1

Views: 806

Answers (1)

Sebastian Weber
Sebastian Weber

Reputation: 6806

Did you consider a non-static class as DI-friendly wrapper around the static UrlHelper class?

public class DynamicUrlHelper
{
  private readonly ISomeDependency dep;
  public DynamicUrlHelper(ISomeDependency dep)
  {
    this.dep = dep;
  }
  public Uri DoMagic(Uri uri)
  {
    return uri.DoMagic(this.dep);
  }
}
public interface ISomeDependency
{
}
public static class UrlHelper
{
  public static Uri DoMagic(this Uri uri, ISomeDependency dep)
  {
    // do it!
    return uri;
  }
}

You can inject the necessary values into DynamicUrlHelper and inject DynamicUrlHelper anywhere it is needed.

Upvotes: 4

Related Questions