Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add extension methods for adding services with custom dependencies #101

Open
wants to merge 1 commit into
base: master
from

Conversation

@luca-esse
Copy link

@luca-esse luca-esse commented Oct 5, 2019

This PR adds extension methods for defining cutom dependencies on specific services.

I came up with this idea because a lot of people didn't like the approach MS have taken with the generic ILogger<T> and the named IOptions<TOptions> (If you have multiple IOptions<TOptions> of the same type you have to retrive the correct instance by name inside of the costructor of the service where they are being injected)

Common usages:

  • Inject the desired service when multiple implementations are registered:
var services = new ServiceCollection();

services.AddSingleton<SomeService1>();
services.AddSingleton<SomeService2>();

services.AddWithDependencies(() =>
{
    services.AddSingleton<MainService>();
}, typeof(SomeService2));

public interface ISomeService { }

public class SomeService1 : ISomeService { }
public class SomeService2 : ISomeService { }

public class MainService 
{
    public MainService(ISomeService someService)
    {
        // someService.GetType() == typeof(SomeService2)
    }
}
  • Avoid injecting the generic ILogger<T>:
var services = new ServiceCollection();

services.AddLogging();

services.AddWithDependencies(() =>
{
    services.AddSingleton<SomeService>();
    services.AddSingleton<SomeOtherService>();
},
(serviceProvider, injectionContext) => new [] {
     serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(injectionContext.CreatingServiceType)
});

public class SomeService
{
    public SomeService(ILogger logger) 
    { 
        // logger.GetType() == typeof(Logger<SomeService>)
    }
}

public class SomeOtherService
{
    public SomeOtherService(ILogger logger) 
    { 
        // logger.GetType() == typeof(Logger<SomeOtherService>)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked issues

Successfully merging this pull request may close these issues.

None yet

1 participant
You can’t perform that action at this time.