.net core DI注入,构造函数含有动态参数

使用.net core 开发的时候我们使用依赖注入来实例化需要的服务等,有时候这个服务类的构造函数是有参数的,此时想使用依赖注入就变得很麻烦。我们可以采用工厂模式,去构造demo如下

  1. 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}";
        }
    }
}

  1. 构造person的接口
namespace DIDynamicConstructorParams.TestDI
{
    public interface DIPersonFactory
    {
        Person CreatePerson(string name,int age, ILogger<Person> logger);
    }
}

  1. 接口实现
namespace DIDynamicConstructorParams.TestDI
{
    public class DI : DIPersonFactory
    {
        public Person CreatePerson(string name, int age,ILogger<Person> logger)
        {
            return new Person(name, age,logger);
        }
    }
}

  1. 注册
builder.Services.AddScoped<DIPersonFactory,DI>();
  1. 依赖注入生成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();
        }
    }
}

https://stackoverflow.com/questions/41669433/net-core-dependency-injection-with-parameters-on-constructor

https://code-maze.com/dotnet-using-constructor-injection/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值