0

I Need To Add A Generic Class With Parameter To IOC Container In Asp.net core But I Don't Know How Do It , My Class Like Bellow And have A Parameter

public class MyClass<T> : IMyclass<T>
{
    string Name {get;}
    public MyClass(string name)
       { 
          Name = name;
       }
}

If I Don't Have Parameter , I Can Add Generic Class To IOC Like Bellow service.AddScoped(typeof(IMyClass<>),typeof(MyClass<>));

But I Need Inject Parameter Like Name To Implementaion I Want Something Like Bellow service.AddScoped(typeof(IMyClass<>),typeof(MyClass<>("Jone Doe"));

the Important Part Is Use A Generic Class And Interface , And Have Parameter Or Prams , And When Add To IOC Idon't know What T Type Going To Create , Now How Can I Do it ?

AMB
  • 21
  • 2
  • Create a new class for the parameters and register it to the DI container, like it is suggested here: https://stackoverflow.com/questions/70628314/injecting-primitive-type-in-constructor-of-generic-type-using-microsoft-di – Dimitris Maragkos Oct 22 '22 at 15:08

1 Answers1

1

It's impossible to construct an open-generic registration using a factory method. You need to create a new class for your parameter and register it to use dependency injection.

For example:

MyClass.cs:

public class MyClass<T> : IMyClass<T> where T : class
    {
        public string Name { get; set; }
        private readonly SetName _setName;

        
        public MyClass(SetName setName)
        {
            _setName = setName;
            Name = _setName.Name;
        }
    }

    public interface IMyClass<T> where T : class
    {
        string Name { get; set; }
    }

SetName.cs:

public class SetName
    {
        public readonly string Name;
        public SetName(string Name)
        {
            this.Name =
                Name ?? throw new ArgumentNullException();
        }
    }

Register Services:

services.AddScoped<SetName>(_ => new SetName("Jone Doe"));
services.AddScoped(typeof(IMyClass<>), typeof(MyClass<>));

Then you can call it via dependency injection:

public class HomeController : Controller
{
    private readonly IMyClass<HomeController> _myclass;
    public HomeController(IMyClass<HomeController> myclass)
    {
        _myclass = myclass;
    }
    public IActionResult Index()
    {
        string testName = _myclass.Name;
        return View();
    }
}

Test Result:

enter image description here

Is this what you expected?

Chen
  • 4,499
  • 1
  • 2
  • 9
  • Isn't [this](https://stackoverflow.com/a/70631949/10839134) the same answer? – Dimitris Maragkos Oct 24 '22 at 09:11
  • Oh, I didn't notice your comment, sorry. The way he registered the parameter class I didn't succeed, so I tossed the answer after changing it. @Dimitris Maragkos – Chen Oct 24 '22 at 09:16