.NET Core 依赖注入

.NET Core 依赖注入


关于IOC和依赖注入
IOC(控制反转)IOC是一种设计思想,类似于描述创建这个对象的方式,IOC框架(Unity、Autofac、Spring.NET,...),控制反转主要控制了对象本身的创建、实例化以及依赖关系,不需要去主动创建,在需要的时候等待容器注入所需的资源,使得项目体系更加松散,降低了耦合,(从主动创建到被动获取,IOC给予)


  • 基于反射 &.NET Core 自带IOC容器实现
public static class GlobalData
{
    public static readonly List<Assembly> AllAssemblies;

    public static readonly List<Type> AllTypes;

    static GlobalData()
    {
        string projectName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        AllAssemblies = (from x in Directory.GetFiles(projectName, "*.dll")
                           where new FileInfo(x).Name.Contains("程序集前缀")
                           select Assembly.LoadFrom(x) into x
                           where !x.IsDynamic
                           select x).ToList();
        AllAssemblies.ForEach(delegate (Assembly aAssembly)
        {
             AllTypes.AddRange(aAssembly.GetTypes());
        });
    }
}

//自定义声明周期特性,不指定情况下默认为Transient
public static class ServiceAttribute : Attribute
{
    public ServiceLifetime Lifetime { get; set; }
    public ServiceAttribute(ServiceLifetime serviceLifetime = ServiceLifetime.Transient) => Lifetime = serviceLifetime;
}


//在ConfigureServices中添加当前方法就能通过自定义特性的方式实现依赖注入 services.AddService()
public static void AddService(this IServiceCollection services)
{
    var types = GlobalData.AllTypes
        .Where(o => o.IsClass && !o.IsAbstract && o.GetCustomAttributes(typeof(ServiceAttribute), false).Length > 0).ToList();

    types.ForEach(item =>
    {
        var lifecycleType = item.GetCustomAttribute<ServiceAttribute>().Lifetime;
        item.GetInterfaces().ToList().ForEach(o =>
        {
            if (lifecycleType is ServiceLifetime.Scoped)
                services.AddScoped(o, item);

            if (lifecycleType is ServiceLifetime.Singleton)
                services.AddSingleton(o, item);

            if (lifecycleType is ServiceLifetime.Transient)
                services.AddTransient(o, item);
        });
    });
}

[Service]
//[Service(ServiceLifetime.Scoped)]
//[Service(ServiceLifetime.Singleton)]
public class Base_UserBusiness : IBase_UserBusiness
{
    //业务逻辑...
}
posted @ 2022-09-19 16:31  科目三考五次  阅读(48)  评论(0编辑  收藏  举报