I am working on an ASP MVC 3 app and I'm writing a custom html helper. It's nothing special or hugely complex, but it will need an instance of an interface from structure map. I know I can simply call into structuremaps' object factory from inside the method, but since the rest of the app uses IoC rather than service location I'd like to keep it that way.
Is there a way to inject interfaces into extension methods from inside and asp net mvc app?
UPDATE
An example of what I'm doing might help:
public static class ShowUrl { public static string ForShow(this UrlHelper url, int showId) { var service = ObjectFactory.GetInstance<IPerformanceService>(); var showName = service.GetPerformanceTitle(showId); return url.Action(MVC.Performance.Details(showId, showName.ToFriendlyUrl())); } }
Which is used like this:
<a href='<%= Url.ForShow(1)%>'>
Essentially I am trying to build a URL with a slug from an entity id. Maybe I'm just going about this in a really daft way.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.
An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.
I would not recommend doing this. Extension methods are generally best used for simple, well-known operations directly on a type. If your extension method is dependent on having an instance of another type, it is likely that it shouldn't be an extension method to begin with.
Consider making an actual service class that performs this functionality, and injecting it where it's needed. If you really need this in an extension method, consider wrapping the functionality your extension method requires in another static class/method, and avoid using any kind of injection or location.
Sharing some code might shed more light on your specific situation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With