.net-core Dependency Injection

前端 未结 5 825
后悔当初
后悔当初 2020-12-16 04:25

I have a Generic repository which I want to register for DI, it implements an interface IRepository.

Normally I would create an instance of it like this:

<         


        
5条回答
  •  没有蜡笔的小新
    2020-12-16 05:18

    What you can do is create an extension method to encapsulate all those individual items that need to be registered.

    That is the same technique Microsoft is using, for example you only put this in startup:

    services.AddMvc();
    

    but that is an extension method and behind the scenes you can bet it is registering a bunch of stuff it needs.

    so you can create your own extension method like this:

    using Microsoft.Extensions.DependencyInjection;
    public static IServiceCollection AddMyFoo(this IServiceCollection services)
    {
        services.AddTransient, DAL.Repository>();
        //....
    
        return services;
    }
    

    and by making the method return the IServiceCollection you make it fluent so you can do

    services.AddMyFoo().AddSomeOtherFoo();
    

    Updated based on comment

    the other technique to reduce registrations is when your dependency doesn't itself have dependencies you can make the constructor have a default of null so you still have decoupling and could pass a different one in later but the DI won't throw an error and you can just instantiate what you need if it is not passed in.

    public class MyFoo(IFooItemDependency myItem = null)
    {
        private IFooItemDependency internalItem;
    
        public MyFoo(IFooItemDependency myItem = null)
        {
            internalItem = myItem ?? new FooItemItem();
        }
    }
    

提交回复
热议问题