IoC:控制反转

接口IIocHelper定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// <summary>
/// Ioc助手接口
/// </summary>
public interface IIocHelper : IDisposable
{
    /// <summary>
    /// 容器
    /// </summary>
    object Container { get; }
 
    /// <summary>
    /// 注册接口
    /// </summary>
    /// <typeparam name="TService">接口类型</typeparam>
    /// <typeparam name="TImplementation">实现类型</typeparam>
    /// <param name="lifestyle">生命周期控制</param>
    void RegisterIoc<TService, TImplementation>(IocLifeStyle lifestyle)
        where TService : class
        where TImplementation : class, TService;
 
    /// <summary>
    /// 根据类型进行接口注册
    /// </summary>
    /// <param name="serviceType">服务类型</param>
    /// <param name="implementationType">实现类型</param>
    /// <param name="iocLifestyle">生命周期控制</param>
    void RegisterIoc(Type serviceType, Type implementationType, IocLifeStyle iocLifestyle);
 
 
 
 
    /// <summary>
    /// 根据接口类型进行注册
    /// </summary>
    /// <typeparam name="TService">服务类型</typeparam>
    /// <param name="funcImpl">实现函数</param>
    /// <param name="iocLifestyle">生命周期控制</param>
    void RegisterIoc<TService>(Func<TService> funcImpl, IocLifeStyle iocLifestyle) where TService:class;
 
 
    /// <summary>
    /// 注册接口,如果接口依赖于其它接口,并且在实现类的汇编级中有相关实现,则会自动注册相关接口
    /// </summary>
    /// <typeparam name="TService">接口类型</typeparam>
    /// <typeparam name="TImplementation">实现类型</typeparam>
    /// <param name="lifestyle">生命周期控制</param>
    void RegisterIocR<TService, TImplementation>(IocLifeStyle lifestyle)
        where TService : class
        where TImplementation : class, TService;
 
    /// <summary>
    /// 根据类型进行接口注册
    /// </summary>
    /// <param name="serviceType">服务类型</param>
    /// <param name="implementationType">实现类型</param>
    /// <param name="iocLifestyle">生命周期控制</param>
    void RegisterIocR(Type serviceType, Type implementationType, IocLifeStyle iocLifestyle);
 
 
    /// <summary>
    /// 获取实例
    /// </summary>
    /// <typeparam name="TInterface">接口类型</typeparam>
    /// <returns>接口实例</returns>
    TInterface GetInstance<TInterface>()
        where TInterface : class;
 
    /// <summary>
    /// 获取类型注册信息
    /// </summary>
    /// <param name="interfaceTye">接口类型</param>
    /// <returns>注册信息</returns>
    IocRegistration GetRegistration(Type interfaceTye);
}

 

实现IocHelper定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
public class IocHelper : IIocHelper, IDisposable
{
    private Container _container;
    protected Dictionary<Type, IocRegistration> _typeRegistrationInfo = new Dictionary<Type, IocRegistration>();
 
    public IocHelper()
    {
        _container = new SimpleInjector.Container();
    }
 
    public object Container
    {
        get
        {
            return _container;
        }
    }
 
    public void Dispose()
    {
        if (_container != null)
        {
            _container.Dispose();
            _container = null;
        }
    }
 
    public TInterface GetInstance<TInterface>()
        where TInterface : class
    {
         return _container.GetInstance<TInterface>();
    }
 
    public IocRegistration GetRegistration(Type serviceType)
    {
        if (_typeRegistrationInfo.ContainsKey(serviceType))
        {
            return _typeRegistrationInfo[serviceType];
        }
        return null;
    }
 
    protected Lifestyle GetLifestyle(IocLifeStyle iocLifestyle)
    {
        Lifestyle lifeStyle = Lifestyle.Scoped;
        switch (iocLifestyle)
        {
            case IocLifeStyle.Scoped:
                lifeStyle = Lifestyle.Scoped;
                break;
            case IocLifeStyle.Singleton:
                lifeStyle = Lifestyle.Singleton;
                break;
            case IocLifeStyle.Transient:
                lifeStyle = Lifestyle.Transient;
                break;
            default:
                throw new NotImplementedException(String.Format("Unknown lifestyle:{0}", Enum.GetName(typeof(IocLifeStyle), iocLifestyle)));
        }
        return lifeStyle;
    }
 
    public void RegisterIoc(Type serviceType,Type implementationType, IocLifeStyle iocLifestyle)
 
    {
        Lifestyle lifeStyle = GetLifestyle(iocLifestyle);
        var prevSettings = GetRegistration(serviceType);
        if (prevSettings == null || prevSettings.ImplementationType!=implementationType)
        {
            _container.Register(serviceType, implementationType, lifeStyle);
            _typeRegistrationInfo[serviceType] = new IocRegistration
            {
                Container = _container,
                ImplementationType = implementationType,
                LifeStyle = iocLifestyle
            };
        }
    }
 
    public void RegisterIoc<TService>(Func<TService> funcImpl, IocLifeStyle iocLifestyle) where TService : class
    {
        Lifestyle lifeStyle = GetLifestyle(iocLifestyle);
        var reg = GetRegistration(typeof(TService));
        if (reg != null) return;
        _container.Register<TService>(funcImpl, lifeStyle);
        _typeRegistrationInfo[typeof(TService)] = new DependencyInjection.IocRegistration
        {
            Container = _container,
            LifeStyle = iocLifestyle,
            ObjectCreator = funcImpl
        };
    }
 
    public void RegisterIoc<TService, TImplementation>(IocLifeStyle iocLifestyle)
        where TService : class
        where TImplementation : class, TService
    {
        RegisterIoc(typeof(TService), typeof(TImplementation), iocLifestyle);
    }
 
    public void RegisterIocR(Type serviceType, Type implementationType, IocLifeStyle iocLifestyle)
    {
        var implClassConstructors = implementationType.GetConstructors(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        var implAssembly = implementationType.Assembly;
        if (implClassConstructors == null || implClassConstructors.Length > 0)
        {
 
            foreach (var implClassConstructor in implClassConstructors)
            {
                var paras = implClassConstructor.GetParameters();
 
                foreach (var para in paras)
                {
                    var t = para.ParameterType;
                    if (t.IsInterface)
                    {
                        var reg = GetRegistration(t);
                        if (reg != null) continue;
                        var matchedClassType = implAssembly.GetExportedTypes().FirstOrDefault(et =>
                         et.IsClass && et.GetInterfaces() != null && et.GetInterfaces().FirstOrDefault(i1 => i1 == t) != null);
                        if (matchedClassType != null)
                        {
                            RegisterIocR(t, matchedClassType, iocLifestyle);
                        }
                        else
                        {
                            var allLoadedAssembly = System.AppDomain.CurrentDomain.GetAssemblies();
                             
                            foreach (var currentAssembly in allLoadedAssembly)
                            {
                                if (currentAssembly.IsDynamic || currentAssembly.GlobalAssemblyCache || currentAssembly.FullName.StartsWith("Microsoft",StringComparison.CurrentCultureIgnoreCase)) continue;
                                matchedClassType = currentAssembly.GetExportedTypes().FirstOrDefault(et =>
                                        et.IsClass && et.GetInterfaces() != null && et.GetInterfaces().FirstOrDefault(i1 => i1 == t) != null);
                                if (matchedClassType!=null)
                                {
                                    RegisterIocR(t, matchedClassType, iocLifestyle);
                                    break;
                                }
                            }
                            if (matchedClassType==null)
                            {
                                throw new InvalidOperationException(String.Format("Unable to register interface {0} in all assemblies while registering interface {1}", t.FullName,serviceType.FullName));
                            }
                        }
                    }
                }
 
            }
        }
 
        RegisterIoc(serviceType, implementationType, iocLifestyle);
 
    }
 
    public void RegisterIocR<TService, TImplementation>(IocLifeStyle iocLifestyle)
        where TService : class
        where TImplementation : class, TService
    {
        RegisterIocR(typeof(TService), typeof(TImplementation), iocLifestyle);
    }
 
 
 
}

  

单例模式获取IocHelper对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class IocFactory
{
    private static IocHelper ioc = null;
 
    public static IIocHelper Instance
    {
        get
        {
            return CreateIocHelper();
        }
    }
 
    private static object _objLock = new object();
 
    public static IIocHelper CreateIocHelper(string IocType = "")
    {
        if (ioc == null)
        {
            lock (_objLock)
            {
                if (ioc == null)
                {
                    if (string.IsNullOrEmpty(IocType))
                    {
                        ioc = new IocHelper();
                    }
                }
            }
        }
        return ioc;
    }
}

  

Global.asax.cs的Application_Start()中使用:

1
2
3
4
5
6
7
8
9
10
11
IIocHelper ioc = IocFactory.Instance;
var actualContainer = ioc.Container as SimpleInjector.Container;
actualContainer.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
var defaultLifeStyle = IocLifeStyle.Transient;
 
ioc.RegisterIoc<ICouponService, CouponService>(defaultLifeStyle);
//.......
 
actualContainer.RegisterMvcControllers(Assembly.GetExecutingAssembly());
actualContainer.RegisterMvcIntegratedFilterProvider();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(actualContainer));

 

 

其他类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/// <summary>
/// LifeStyle
/// </summary>
public enum IocLifeStyle:Int32
{
    /// <summary>
    /// Scoped
    /// </summary>
    Scoped = 0,
 
    /// <summary>
    /// Singleton
    /// </summary>
    Singleton = 1,
 
    /// <summary>
    /// Transient
    /// </summary>
    Transient = 2
}
 
 
 
 
 
 /// <summary>
/// Ioc注册信息
/// </summary>
public class IocRegistration
{
    /// <summary>
    /// 生命周期类型
    /// </summary>
    public IocLifeStyle LifeStyle { get; set; }
    /// <summary>
    /// 实现类型
    /// </summary>
    public Type ImplementationType { get; set; }
    /// <summary>
    /// 容器
    /// </summary>
    public Object Container { get; set; }
    /// <summary>
    /// 对象创建方法
    /// </summary>
    public Object ObjectCreator { get; set; }
}

  

 

 

 

posted @   PanPan003  阅读(361)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示