使用.net core 开发的时候我们使用依赖注入来实例化需要的服务等,有时候这个服务类的构造函数是有参数的,此时想使用依赖注入就变得很麻烦。我们可以采用工厂模式,去构造demo如下
- person类
namespace DIDynamicConstructorParams.TestDI
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
private ILogger<Person> _loggerFactory;
public Person(string name,int age, ILogger<Person> loggerFactory)
{
Name = name;
Age = age;
_loggerFactory = loggerFactory;
}
public string SayHello()
{
_loggerFactory.LogInformation("just a test");
return $"hello {Name},my age is {Age}";
}
}
}
- 构造person的接口
namespace DIDynamicConstructorParams.TestDI
{
public interface DIPersonFactory
{
Person CreatePerson(string name,int age, ILogger<Person> logger);
}
}
- 接口实现
namespace DIDynamicConstructorParams.TestDI
{
public class DI : DIPersonFactory
{
public Person CreatePerson(string name, int age,ILogger<Person> logger)
{
return new Person(name, age,logger);
}
}
}
- 注册
builder.Services.AddScoped<DIPersonFactory,DI>();
- 依赖注入生成person类
using DIDynamicConstructorParams.TestDI;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace DIDynamicConstructorParams.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class DIController : ControllerBase
{
private readonly DIPersonFactory _dIPersonFactory;
private ILogger<Person> _loggerFactory;
public DIController(DIPersonFactory dIPersonFactory, ILogger<Person> loggerFactory)
{
_dIPersonFactory = dIPersonFactory;
_loggerFactory = loggerFactory;
}
[HttpGet]
public string Test([FromQuery] string Name, [FromQuery] int Age)
{
Person person = _dIPersonFactory.CreatePerson(Name, Age,_loggerFactory);
return person.SayHello();
}
}
}