IOC的作用这里省略…只对如何使用进行说明。
IOC
这里使用 .NET6.0 WebAPI 应用
.NET6.0 WebAPI
public interface IAuthService { bool CheckToken(); }
public interface IAuthService
{
bool CheckToken();
}
class AuthServiceImpl : IAuthService{ public bool CheckToken() { Console.WriteLine("check token"); return true; }}
class AuthServiceImpl : IAuthService
public bool CheckToken()
Console.WriteLine("check token");
return true;
下面是在 program 类中的代码
program
var services = new ServiceCollection();services.AddSingleton<IAuthService, AuthServiceImpl>();
var services = new ServiceCollection();
services.AddSingleton<IAuthService, AuthServiceImpl>();
通过在 Controller的构造函数中注入IAuthService
Controller
IAuthService
private readonly IAuthService _service; public WeatherForecastController(IAuthService service) { _service = service; } [HttpGet(Name = "test")] public bool Get() { return _service.CheckToken(); }
private readonly IAuthService _service;
public WeatherForecastController(IAuthService service)
_service = service;
[HttpGet(Name = "test")]
public bool Get()
return _service.CheckToken();
启动后,通过swagger发起请求,验证接口。
swagger
基本IOC容器流程已实现。但是这样存在一个弊端,每个接口和实现都要在program中手动注册一遍,还要在Controller构造函数中进行依赖注入,有没有能自动实现注册代替program中的手动注册?
IOC容器
接下来,对上述流程进行改良。
定义一个AutowiredAttribute标记,通过Atrribute标记的方式,在实现类上标记其要实现的接口服务,然后实现一个服务加载类ServiceLoader,在这个类中反射获取所有具备AutoIocAttribute的实现类,然后注册到ServiceCollection中。
AutowiredAttribute
Atrribute
ServiceLoader
AutoIocAttribute
ServiceCollection
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public class AutowiredAttribute : Attribute { /// <summary> /// 接口 /// </summary> public Type Iface { get; set; } /// <summary> /// 实现类名 /// </summary> public string ImplClassName { get; set; } public AutowiredAttribute(Type iface, [CallerMemberName] string implClassName = "") { Iface = iface; ImplClassName = implClassName; } }
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class AutowiredAttribute : Attribute
/// <summary>
/// 接口
/// </summary>
public Type Iface { get; set; }
/// 实现类名
public string ImplClassName { get; set; }
public AutowiredAttribute(Type iface, [CallerMemberName] string implClassName = "")
Iface = iface;
ImplClassName = implClassName;
利用IServiceCollection作为服务容器
IServiceCollection
public class ServiceLoader { private static object _lock = new object(); private static AppRuntime _inst; private readonly IServiceCollection _iocService = new ServiceCollection(); private readonly ICollection<Assembly> _iocAssembly = new HashSet<Assembly>(); private IServiceProvider _iocServiceProvider = null; public static ServiceLoader Instance { get { if (_inst == null) { lock (_lock) { _inst = new ServiceLoader(); _inst.Startup(typeof(ServiceLoader).Assembly); } } return _inst; } } public T GetService<T>() { EnsureAutoIoc<T>(); return _iocServiceProvider.GetService<T>(); } private void EnsureAutoIoc<T>() { Startup(typeof(T).Assembly); } public void Startup(Assembly ass) { if (_iocAssembly.Any(x => x == ass)) { return; } _iocAssembly.Add(ass); var types = ass.GetTypes().Where(x => x.GetCustomAttribute<AutowiredAttribute>() != null); foreach (var item in types) { var autoIocAtt = item.GetCustomAttribute<AutowiredAttribute>(); AddTransient(autoIocAtt.Iface, item); } //_iocServiceProvider = _iocService.BuildServiceProvider(); Interlocked.Exchange(ref _iocServiceProvider, _iocService.BuildServiceProvider()); } private void AddTransient(Type iface, Type impl) { _iocService.AddTransient(iface, impl); } }
public class ServiceLoader
private static object _lock = new object();
private static AppRuntime _inst;
private readonly IServiceCollection _iocService = new ServiceCollection();
private readonly ICollection<Assembly> _iocAssembly = new HashSet<Assembly>();
private IServiceProvider _iocServiceProvider = null;
public static ServiceLoader Instance
get
if (_inst == null)
lock (_lock)
_inst = new ServiceLoader();
_inst.Startup(typeof(ServiceLoader).Assembly);
return _inst;
public T GetService<T>()
EnsureAutoIoc<T>();
return _iocServiceProvider.GetService<T>();
private void EnsureAutoIoc<T>()
Startup(typeof(T).Assembly);
public void Startup(Assembly ass)
if (_iocAssembly.Any(x => x == ass))
return;
_iocAssembly.Add(ass);
var types = ass.GetTypes().Where(x => x.GetCustomAttribute<AutowiredAttribute>() != null);
foreach (var item in types)
var autoIocAtt = item.GetCustomAttribute<AutowiredAttribute>();
AddTransient(autoIocAtt.Iface, item);
//_iocServiceProvider = _iocService.BuildServiceProvider();
Interlocked.Exchange(ref _iocServiceProvider, _iocService.BuildServiceProvider());
private void AddTransient(Type iface, Type impl)
_iocService.AddTransient(iface, impl);
[Autowired(typeof(IAuthService))] class AuthServiceImpl : IAuthService { public bool CheckToken() { Console.WriteLine("check token"); return true; } }
[Autowired(typeof(IAuthService))]
var svc = ServiceLoader.Instance.GetService<IAuthService>(); svc.CheckToken();
var svc = ServiceLoader.Instance.GetService<IAuthService>();
svc.CheckToken();
至此一个基本的完整IOC容器已实现。
本文来自博客园,作者:宣君{https://www.nhit.icu/},转载请注明原文链接:https://www.cnblogs.com/ycit/p/17680238.html
原文链接:https://www.cnblogs.com/ycit/p/17680238.html
本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728