Asp.net Core 2.1(DI)依赖注入ServiceCollection

时间:2018-06-08 14:03:53

标签: asp.net .net dependency-injection core asp.net-core-2.1

我正在玩Asp.net Core 2.1 我只想确认这是否是ServiceCollection的错误实现?

欢迎提出建议和更正:)

我创建了一个BusinessContractFactory来解析我的特定服务。

 public T GetInstance<T>() where T : IBusinessContracts
    {                     
        return ServiceObjectBase.ResolveService<T>();
    }

bellow是我的ServiceObjectBase类

public abstract class ServiceObjectBase 
{
    public ServiceObjectBase()
    {

    }
    /// <summary>
    /// Resolve the service of T from the IServiceProvider
    /// </summary>
    /// <typeparam name="T"></typeparam>        
    /// <returns>
    /// </returns>
    public static T ResolveService<T>()
    {
        var provider = GetServices().BuildServiceProvider();

        return provider.GetService<T>();

    }
    /// <summary>
    /// Private Property Service Collection
    /// </summary>
    private static IServiceCollection _serviceCollection { get; set; }
    ///// <summary>
    ///// Get Service Collection
    ///// </summary>
    ///// <returns></returns>  
    private static IServiceCollection GetServices()
    {
        //New instance of Service Collection
        _serviceCollection = new ServiceCollection();

        /*
         Add your Service Collection here
        */
        _serviceCollection.AddBusinessLayerServices();

        return _serviceCollection;
    }

}
在我的StartUp.cs类中

public void ConfigureServices(IServiceCollection services)
    {          

        services.AddMvc();

        services.AddSingleton<IBusinessContractFactory, BuisnessContractFactory>();

    }

和我的API控制器

public class ValuesController : Controller
{
    private readonly IBusinessContractFactory _businessFactory;
    public ValuesController(IBusinessContractFactory businessFactory)
    {
        _businessFactory = businessFactory;
    }
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        var sampleA = _businessFactory.GetInstance<ISampleA>();

        sampleA.BuildA();

        var sampleB = _businessFactory.GetInstance<ISampleB>();

        sampleB.BuildB();

        var sampleC = _businessFactory.GetInstance<ISampleC>();

        sampleC.SampleCFunction();

        return new string[] { "value1", "value2" };
    }  
  }

TIA分享你对这个实现的想法纠正我,如果我错了所以我可以改进。

0 个答案:

没有答案