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