Click here to Skip to main content
15,501,036 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have Interface like

public interface IMyContext<TEntity> where TEntity : class{
}

and class like
public partial class MyContext<TEntity> : IMyContext<TEntity> where TEntity : class
    {

 public MyContext(string str)
        {
           
        }

}



how can i pass dependecy in IServiceCollection of .net core. I want to pass str also

What I have tried:

services.AddScoped(typeof(IMyContext<>), typeof(MyContext<>));
             services.AddScoped<typeof(IMyContext<>)>(provider => new MyContext("connection")));
Posted
Updated 27-Oct-21 3:38am
v2

1 solution

There is currently no support for using a factory with an open generic type. There's an open issue on GitHub discussing this:

Dependency Injection of Open Generics via factory · Issue #41050 · dotnet/runtime · GitHub[^]

I'd suggest using another class to inject the parameter into your constructor. For example:
C#
public class MyContextOptions
{
    public MyContextOptions(string value)
    {
        Value = value;
    }
    
    public string Value { get; }
}

public partial class MyContext<TEntity> : IMyContext<TEntity> where TEntity : class
{
    public MyContext(MyContextOptions options)
    {
           
    }
}
C#
services.AddSingleton(new MyContextOptions("connection"));
services.AddScoped(typeof(IMyContext<>), typeof(MyContext<>));
 
Share this answer
 
Comments
BillWoodruff 27-Oct-21 12:00pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900