weidazhao / Hosting

Hosting prototype
170 stars 35 forks source link

Services from the ServiceCollection provider #36

Closed fleed closed 8 years ago

fleed commented 8 years ago

How should I access services defined within the ServiceCollection defined in the Asp.Net application? Is it a good (or bad) practice accessing it from a runtime perspective?

weidazhao commented 8 years ago

Do you mean the Service Fabric services that are registered via Startup.ConfigureServices()? If yes, you can get them from HttpContext.RequestServices. MVC has dependency injection built in so you don't need to explicitly call HttpContext.RequestServices to get the service. Instead you just require the service in the constructor of a controller as a parameter, like https://github.com/weidazhao/Hosting/blob/master/Counter/Controllers/CounterController.cs#L11.

fleed commented 8 years ago

Sorry, my question was a little bit vague. I'd like to use an additional service within a Stateful or Stateless service, with the Asp.Net Core DI constructing it, like this:

    public interface IMyService
    {
        void DoSomething();
    }

    public class CounterService : StatefulService, ICounterService
    {
        private readonly AspNetCoreCommunicationContext _communicationContext;
        private readonly SemaphoreSlim _semaphore;
        private readonly IMyService myService;

        public CounterService(StatefulServiceContext serviceContext, AspNetCoreCommunicationContext communicationContext,
        IMyService myService /* should be injected by MVC */)
            : base(serviceContext)
        {
            _communicationContext = communicationContext;
            _semaphore = new SemaphoreSlim(1, 1);
            this.myService = myService;
        }

        public async Task<long> GetCurrentAsync()
        {
            this.myService.DoSomething();
            // everything else
        }
    }

I could pass the service as argument to methods, but injecting it through the DI mechanism would a much more elegant solution. Is it possible?

weidazhao commented 8 years ago

Service Fabric doesn't support DI with https://github.com/aspnet/DependencyInjection now.

fleed commented 8 years ago

Thanks, I can close the issue but I hope that you will consider it as feature request.