Skip to content

Instantly share code, notes, and snippets.

@bbarry
Created November 13, 2019 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbarry/ae9ac27e56306005ff2285a6d4c4344e to your computer and use it in GitHub Desktop.
Save bbarry/ae9ac27e56306005ff2285a6d4c4344e to your computer and use it in GitHub Desktop.
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ServiceFactory
{
public interface IServiceFactory<T>
{
T GetService();
}
internal class ContainerServiceFactory<T> : IServiceFactory<T>
{
readonly IServiceProvider _services;
public ContainerServiceFactory(IServiceProvider services) => _services = services;
public T GetService() => _services.GetRequiredService<T>();
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceFactoryServiceCollectionExtensions
{
public static IServiceCollection AddServiceFactory(this IServiceCollection services)
{
services.AddSingleton(typeof(IServiceFactory<>), typeof(ContainerServiceFactory<>));
return services;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment