Best way to reorganize this static class in C #?

The following is an example of a static class.

public static class BackgroundTaskExecuter { public static void MethodA() { using (var service = IocManager.Instance.ResolveAsDisposable<IServiceA>()) { service.Object.MethodA(); } } public static void MethodB() { using (var service = IocManager.Instance.ResolveAsDisposable<IServiceB>()) { service.Object.MethodB(); } } public static void MethodC() { using (var service = IocManager.Instance.ResolveAsDisposable<IServiceC>()) { service.Object.MethodC(); } } } 

As you can see, I have three methods. MethodA , MethodB and MethodC , which correspond to three different interfaces IServiceA , IServiceB and IServiceC

The reason I do this is because I use Hangfire.io with the aspnetboilerplate framework and in Hangfire, the background task does not have an HttpContext from a regular dependency injection. Creating a static class that transfers my calls, where I decide manually, seems to get around this.

Usage is as follows:

 BackgroundJob.Enqueue(() => BackgroundTaskExecuter.MethodA()); 

Currently, I only have one or two background tasks in my web application, but maybe I can have a lot more in the future, and while it will serve now, it will be ugly if I save this an approach.

Is there a better way to do this / reorganize it? A factory template or something like that is possible?

Thanks.

+7
c # asp.net-mvc hangfire
source share
1 answer

I would make the static wrapper general and simple. Let it expose one method that enables the service and consumes it using the using statement, allowing the caller to invoke the instance passed to Action<T> .

A source

 public static class BackgroundTaskExecuter { public static void ResolveAndConsume<T>(Action<T> consumeService) { // Consider applying constraint to the <T> to // match the constraint of ResolveAsDisposable<T> using (var service = IocManager.Instance.ResolveAsDisposable<T>()) { consumeService(service); } } } 

Usage example

 BackgroundJob.Enqueue(() => BackgroundTaskExecuter.ResolveAndConsume<IServiceA>(serviceA => serviceA.MethodA())); 

Using the above, you can enable and use the service implementation and call its functionality as desired.

+6
source share

All Articles