【问题标题】:net core 2.1 Dependency injectionnet core 2.1 依赖注入
【发布时间】:2019-06-05 06:29:28
【问题描述】:

我有 dot net core 项目,我想在我的 Controller IContextDb 中注入

我有很多类继承自 IContextDb 即(ShopContext,UserContext,..):IContextDb

我的问题是:

1 - 有没有办法在正确的控制器中注入正确的上下文 在我的控制器中实时注入上下文

我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services.AddTransient<IContextDb>(
    serviceProvider => 
      {
         /// to do to map IContextDb with right context for
         /// right controller 
         /// or using reflection  
       });
    services.AddOptions();
    services.AddMvc();
  }

我的 MVC 控制器:

public class UserController
{
    private IContextDb _userContext
    public UserController(IContextDb userContext)
    {
       _userContext = userContext;
    }
}

【问题讨论】:

    标签: c# dependency-injection .net-core


    【解决方案1】:

    只需在每个控制器中注入具体类

    public class UserController
    {
        private IContextDb _userContext
        public UserController(UserContext userContext)
        {
           _userContext = userContext;
        }
    }
    

    【讨论】:

      【解决方案2】:

      经过几天的研究,我发现了如何注入我所有的班级

      无需手动操作:使用组装和反射

      stratup.cs

      public void ConfigureServices(IServiceCollection services)
      {
          /// I call the function register all class I want to be injected
          RegisterAllContext(services);
      }
      

      /// 注册所有要注入的类的功能

       public void RegisterAllContext(IServiceCollection services)
          {         
              // load assemblies
              var assemblies = AppDomain.CurrentDomain.GetAssemblies();
      
               // Get Dal assembly (class assembly want to be injected)
                var dalAssembly = assemblies.FirstOrDefault(assembly => assembly.GetName().Name == "DAL.UOF");
      
      //registre all class with attribut inject 
      // in the service to be injected.
      
          if (dalAssembly != null)
            {
               // Filter All assemblie type 
               // 1- by type is class 
               // 2- by type has CustomAttributes ("InjectableAttribute" in my case)
      
      
               var assemblieTypesNameContaintContext = from type in dalAssembly.GetTypes()
               where type.IsClass && type.CustomAttributes.Any(
                      a =>{ return a.AttributeType == typeof(InjectableAttribute); })
               select type;
      
            // registre in net core injector service 
               foreach (var typeNameContaintContext in assemblieTypesNameContaintContext.ToList())
             {
                // get full Name assemblie type and
                // add it to the service.
      
                  /// typeName == ClassFullName, assemblie Name
                  /// Assemblie Name is necessary if the class
                  /// in not int the same assemblie (assemblie name : "DAL.UOF" in my case)
                  var typeName = typeNameContaintContext.FullName + ",DAL.UOF";
                  var type = Type.GetType(typeName);
                  if (type != null)
                  {
                      services.AddTransient(type, type);
                  }
                  else
                  {
                    Console.WriteLine("type is null");
                  }
            }
      }
      

      具有可注入属性的类

       [Injectable]
              MyClassToInject
              {
                ......
              }
      

      【讨论】:

        【解决方案3】:

        要将 DbContext 添加到您的应用,请使用以下示例:

        var connection = Configuration.GetConnectionString("DefaultDbConnection");
                services.AddDbContext<ShopContext>(options =>
                    options.UseSqlServer(connection));
        

        在你的控制器中

        public class UserController
        {
            private ShopContext_userContext
            public UserController(ShopContext userContext)
            {
               _userContext = userContext;
            }
        }
        

        您可以通过这种方式注入 manu 上下文,或者只创建一个来管理许多表。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-22
          • 1970-01-01
          • 2018-11-23
          • 2018-11-16
          • 2021-10-23
          • 1970-01-01
          • 2021-02-02
          • 1970-01-01
          相关资源
          最近更新 更多