.net core依赖注入构造函数传参

public class MyClass
    {
        private readonly ILogger _logger;
        private readonly YourClass _your;
        ServiceCollection services = new ServiceCollection();
        private string yourname = string.Empty;

        private string _shengmiao;
        public MyClass(ILogger<MyClass> logger,YourClass your,string shengmiao)
        {
            _logger = logger;
            _your=your;
            _shengmiao=shengmiao;
            yourname = shengmiao;
        }

        public void SomeMethod()
        {
            _logger.LogInformation(_shengmiao);
            _logger.LogInformation("Hello" + yourname);
            _your.DoYourThings();
        }
    }
class Program
    {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();
            var myClass = serviceProvider.GetService<MyClass>();
            myClass.SomeMethod();
            System.Console.WriteLine("Done1");
            Console.ReadKey();
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(configure => configure.AddConsole())
                            .AddTransient<YourClass>()
                            .AddTransient<MyClass>(
                            //此处是关键,主动获取需要构造的类型,然后传进去
                                x=>
                                new MyClass(x.GetRequiredService<ILogger<MyClass>>(),
                                x.GetRequiredService<YourClass>(),
                                "1234567890098"));
        }
    }
    ```
```C#
    public class YourClass
    {
         private readonly ILogger _logger;

        public YourClass(ILogger<YourClass> logger)
        {
            _logger = logger;
        }

        public void DoYourThings()
        {
            _logger.LogInformation("Hello Your Word");
        }

    }

https://stackoverflow.com/questions/53884417/net-core-di-ways-of-passing-parameters-to-constructor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值