Hello,
I need to inject a service on static class, how can I do that ?
On my mvc app I am injecting my services on the Controllers as said on docs, but I need to use some statics classes as data providers (I am using DevExpress component for UI), so How can I inject my service in there?
Today I am doing like this: (I don't like it)
Controller
private static IGerenciadorBoletadorService _gerenciadorBoletadorService;
public DashboardController(IGerenciadorBoletadorService gerenciadorBoletadorService)
{
//static property on PineCalendarioDataProvider.cs
PineCalendarioDataProvider._gerenciadorBoletadorService = gerenciadorBoletadorService;
}
Thanks
3 Answer(s)
-
0
You can not use injection for static classes. But you can use service locator pattern. Example:
public static class MyStaticClass { private static MyService _myService; static MyStaticClass() { _myService = IocManager.Instance.Resolve<MyService>(); } public static void DoIt() { //use _myService here... } }
-
0
Oh, great..
And should I use the "IocManager.Instance.Release(myService);" after use?
as said on Resolve method Summary
Thanks a lot
-
0
No need to release for static classes. Because static classes are not disposed. When do you know it's not needed anymore? If you can know it, yes release it.
Also, you may consider to Resolve it when needed in DoIt method and then release after usage (Use ResolveAsDisposable method for it: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Dependency-Injection#DocIocHelper">http://www.aspnetboilerplate.com/Pages/ ... cIocHelper</a>).
But, as a best practice, avoid static classes wherever possible.