ASP.NET Core option dependency in constructor

前端 未结 2 540
感动是毒
感动是毒 2021-01-15 04:19

I\'m using ASP.NET Core and I\'m attempting to create a resolvable class which has an optional parameter:

public class Foo
{
     public Foo() : this(null)
          


        
相关标签:
2条回答
  • 2021-01-15 04:43

    I think its general behavior of Containers to resolve the constructor with the most parameters.

    Basically what AddTransient does is the following:

    services.AddTransient<Foo>();
    //equals to:
    services.AddTransient<Foo>(c=> new Foo(c.GetService<IValidator<FooEntity>()));
    

    So you can register it yourself like this:

    services.AddTransient<Foo>(c=> new Foo());
    

    At this point in the startup class you should know if IValidator<FooEntity> has been registered. Or, if you are using reflection add this logic to your reflection code.

    Difference

    The difference between the 2 options is that with the first option is that the lambda function to resolve the class is created on startup. + if you change the constructor no code needs to be changed elsewhere.

    If you create the lambda yourself this lambda is compiled on build, so theoretically startup should be faster (I have not tested this).

    Great mindset

    A great mindset is to own the libraries you are using. In Visual studio/Resharper you can decompile source-code, or you can find the repositories on github nowadays.

    There you can see the source code, you can see how the services parameters is 'compiled' to the IServiceProvider (see BuildServiceProvider() method, it will give you alot of insight.)

    Also look at:

    • ServiceDescriptor, Your type registration.
    • Service, the one that resolves the type.

    Solution

    best way to do it is this, (sorry for psuedo code but i have no editor at hand).

    getTypes()
        .Where(x=> x.EndsWith("Entity") //lets get some types by logic
        .Select(x=> typeof(IValidator<>).MakeGeneric(x)) //turn IValidator into IValidator<T>
        .Where(x=> !services.IsRegistered(x))
        .Each(x=> services.Add(x, c=> null)) //register value null for IValidator<T> 
    
    0 讨论(0)
  • 2021-01-15 04:46

    You need to register the IValidator<T> first:

      var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
      services.AddTransient<IValidator<FooEntity>, RealValidator<FooEntity>>();
      services.AddTransient<Foo>();
    
      var serviceProvider = services.BuildServiceProvider();
      var validator = serviceProvider.GetService<IValidator<FooEntity>>();
      var foo = serviceProvider.GetService<Foo>();
    
      Assert.NotNull(validator);
      Assert.NotNull(foo);
    
    0 讨论(0)
提交回复
热议问题