IOC批量注入再Core框架中還是比較麻煩的,因此寫了一個簡單的IOC注入通過屬性標注服務,再通過service自帶的注冊服務,擴展了三個注入服務,分別為
AddServiceInjectTransientSetup/AddServiceInjectScopedSetup/AddServiceInjectSingletonSetup下面直接上代碼
ServiceInjectSetup類
public static class ServiceInjectSetup
{
public static void AddServiceInjectTransientSetup(this IServiceCollection services, System.Reflection.Assembly assembly)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
foreach (Type item in assembly.GetTypes())
{
Transient attribute = item.GetCustomAttribute(typeof(Transient)) as Transient;
if (attribute != null)
{
services.AddTransient(attribute.ServiceType, item);
}
}
}
public static void AddServiceInjectScopedSetup(this IServiceCollection services, System.Reflection.Assembly assembly)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
foreach (Type item in assembly.GetTypes())
{
Scoped attribute = item.GetCustomAttribute(typeof(Scoped)) as Scoped;
if (attribute != null)
{
services.AddScoped(attribute.ServiceType, item);
}
}
}
public static void AddServiceInjectSingletonSetup(this IServiceCollection services, System.Reflection.Assembly assembly)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
foreach (Type item in assembly.GetTypes())
{
Singleton attribute = item.GetCustomAttribute(typeof(Singleton)) as Singleton;
if (attribute != null)
{
services.AddSingleton(attribute.ServiceType, item);
}
}
}
}
自定義屬性
public class Transient : Attribute
{
public Type ServiceType { get; set; }
public Transient(Type serviceType)
{
ServiceType = serviceType;
}
}
public class Singleton : Attribute
{
public Type ServiceType { get; set; }
public Singleton(Type serviceType)
{
ServiceType = serviceType;
}
}
public class Scoped : Attribute
{
public Type ServiceType { get; set; }
public Scoped(Type serviceType)
{
ServiceType = serviceType;
}
}
再startup類調用服務
services.AddServiceInjectScopedSetup(this.GetType().Assembly);
services.AddServiceInjectTransientSetup(this.GetType().Assembly);
services.AddServiceInjectSingletonSetup(this.GetType().Assembly);
標注服務
[Scoped(serviceType: typeof(ItestRepository))]
public class TestServices : ItestRepository
{
public string test()
{
return "張三";
}
}
再控制器中使用即可,有很多種注入方式,我比較喜歡的這種方式