zoukankan      html  css  js  c++  java
  • .net core 依赖注入扩展,实现随处控制反转

    在使用.net core时,依赖注入,主要使用通过构造函数注入。小编将通过扩展方式,实现在类中各个地方可以控制反转,获取实例。

    1、首先自定义扩展类

    1. using Microsoft.AspNetCore.Builder;

    2. using System;

    3. namespace Microsoft.Extensions.DependencyInjection

    4. {

    5. public static class DI

    6. {

    7. public static IServiceCollection Services { get; set; }

    8. public static IServiceProvider ServiceProvider { get; set; }

    9. }

    10. public static class Extensions

    11. {

    12. public static IServiceCollection AddTfDI(this IServiceCollection services)

    13. {

    14. DI.Services = services;

    15. return services;

    16. }

    17. public static IApplicationBuilder UseTfDI(this IApplicationBuilder builder)

    18. {

    19. DI.ServiceProvider = builder.ApplicationServices;

    20. return builder;

    21. }

    22. }

    23. }

    2.在startup.cs中的public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)中添加

    app.UseTfDI();//依赖注入扩展方法

    3.实例教你如何使用

    假设我们在有一个依赖注入:

    services.AddSingleton<IUploadHelper, UploadHelper>();

    那么我们在其他需要调用的类中,就可以通过

    var up = DI.ServiceProvider.GetRequiredService<IUploadHelper>(); //这样即可以获得实例

    很简单吧,说明一下,在.net core2中,通过该 方法暂不支持services.AddScoped 注入方式的控制反转。

    .net core 依赖注入扩展,实现随处控制反转

    更多精彩文章请关注我们的微信公众号FocusDotCore

  • 相关阅读:
    为Mac Terminal设置代理
    Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo
    vue.js环境搭建
    nodejs实现的简单接口
    Runtime
    iOS -- 神战
    前端视频
    iOS-- 重要的链接
    Oracle 11g R2安装手册(图文教程)For Windows
    undo_retention:确定最优的撤销保留时间
  • 原文地址:https://www.cnblogs.com/tianfengcc/p/7851940.html
Copyright © 2011-2022 走看看