- 从构造函数中获取实例;
private readonly IRabbitMqConnectionFactory _connectionFactory; public OrderService(IRabbitMqConnectionFactory connectionFactory) { _connectionFactory = connectionFactory; }
- 封装一个Global静态类
public static class Global { public static IApplicationBuilder Application { get; set; } public static IServiceProvider Services { get; set; } public static T GetService<T>() { if (typeof(T).GetInterfaces().Contains(typeof(IScoped))) { using (var scope = Services.CreateScope()) { return scope.ServiceProvider.GetRequiredService<T>(); } } return Services.GetService<T>(); } public static void UseGlobal(this IApplicationBuilder app) { Application = app; Services = app.ApplicationServices; } }
-
中间件引用, 主要是将collection中实例都塞到静态属性Services中。
app.UseGlobal();
-
需要使用到实例的地方直接获取
var _connectionFactory = Global.GetService<IRabbitMqConnectionFactory>();
- 优势:对于当前实现类的生命周期是非singleton的可以避免在构造函数中获取在某些方法使用不到的实例