Skip to content

Instantly share code, notes, and snippets.

@McTristan
Created May 16, 2019 09:52
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 McTristan/f240cb50db1bcf76f8d5e86695b440b8 to your computer and use it in GitHub Desktop.
Save McTristan/f240cb50db1bcf76f8d5e86695b440b8 to your computer and use it in GitHub Desktop.
using System;
using Microsoft.Extensions.DependencyInjection;
namespace ViMobile.Utilities.DependencyInjection
{
public static class IoCNew
{
private static readonly ServiceCollection ServiceCollection;
static IoCNew()
{
ServiceCollection = new ServiceCollection();
}
public static ServiceProvider Container { get; }
public static T Get<T>()
{
var container = ServiceCollection.BuildServiceProvider();
return container.GetService<T>();
}
public static void Register<TInterface, TImplementation>(bool asSingleton = true)
where TImplementation : class, TInterface where TInterface : class
{
if (asSingleton)
{
ServiceCollection.AddSingleton<TInterface, TImplementation>();
}
else
{
ServiceCollection.AddScoped<TInterface, TImplementation>();
}
}
public static void Register<TImplementation>(bool asSingleton = true) where TImplementation : class
{
if (asSingleton)
{
ServiceCollection.AddSingleton<TImplementation>();
}
else
{
ServiceCollection.AddScoped<TImplementation>();
}
}
public static void Register<TInterface>(TInterface instance) where TInterface : class
{
ServiceCollection.AddSingleton(instance);
}
public static void RegisterOpenType(Type interfaceType, Type implementationType)
{
ServiceCollection.AddSingleton(interfaceType, implementationType);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment