sam
sam

Reputation: 31

net core 2.1 Dependency injection

I have dot net core project , I want to inject in my Controller IContextDb

I have many class inherit from IContextDb ie (ShopContext, UserContext, ..) : IContextDb

My Question is :

1 - Is there way to inject the right context in the right Controller to inject the context in my controller in real time

My 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();
  }

My MVC Controller :

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

Upvotes: 1

Views: 1545

Answers (3)

Kornylevych Andriy
Kornylevych Andriy

Reputation: 1

To add DbContext to your app, use this sample:

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

And in your controller

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

You may inject manu context in such way, or just create one, that will manage many tables.

Upvotes: 0

sam
sam

Reputation: 31

After some days of research I found how i can inject all my class

without do it manually: with assembly and reflection

stratup.cs

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

/// function to registre all class to be injected

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

class with injectable attribut

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

Upvotes: 0

Carlos Mu&#241;oz
Carlos Mu&#241;oz

Reputation: 17844

Just inject the concrete class in each controller

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

Upvotes: 1

Related Questions