net core 2.1依赖注入

时间:2018-04-24 18:46:23

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

我有点网核心项目,我想注入我的Controller IContextDb

我有很多类继承自IContextDb ie(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;
    }
}
坦克提前

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

经过几天的研究后,我发现我可以注入所有课程

无需手动执行:使用装配和反射

<强> stratup.cs

<div class='container'>
  <div class='content'>
   <h1>Content</h1>
  </div>
  <div class='overlay'>
  </div>
</div>

/// 注册所有要注入的课程的功能

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");
            }
      }
}

答案 2 :(得分:0)

要将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上下文,或者只创建一个manu上下文,它将管理许多表。