• 在控制台下玩玩dotnet core内置原生的DI


    转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/

    在基于dotnet core的web开发中,我们会经常用到DI,那么如果单单使用dotnet core自身提供的一整套DI程序,该如何来实现呢?
    直接上代码吧:

    public interface IBar
    {
        void MethodOne();
    
        void MethodTwo();
    }
    public class Bar : IBar
    {
        public void MethodOne()
        {
            Console.WriteLine("MethOne....");
        }
    
        public void MethodTwo()
        {
            Console.WriteLine("MethTwo....");
        }
    }
    View Code

    我们写个控制器类:

    public class MianController
    {
        private IServiceCollection _services;
        private IServiceProvider _serviceProvider;
        private IBar _bar;
    
        public MianController(IServiceCollection services)
        {
            _services = services;
            _serviceProvider = _services.BuildServiceProvider();
            _bar = _serviceProvider.GetService<IBar>();
        }
    
        public void ActionOne()
        {
            _bar.MethodOne();
        }
    
        public void ActionTwo()
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var bar = scope.ServiceProvider.GetService<IBar>();
                bar.MethodTwo();
            }
    
        }
    
    }
    main函数:
    static void Main(string[] args)
    {
        IServiceCollection services = new ServiceCollection();
        services.AddScoped<IBar, Bar>();
    
        var controller = new MianController(services);
        controller.ActionOne();
        controller.ActionTwo();
    
        Console.Read();
    }

    这里用到了正常的DI方法也有少用的CreateScope方法,这两者都是用来获取指定服务的。具体可以参考  asp.net core 依赖注入实现全过程粗略剖析(3)

    转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/

  • 相关阅读:
    [Leetcode] Copy List with Random Pointer
    [Java] StringBuffer类
    [Leetcode] Wildcard Matching
    [Leetcode] Substring with Concatenation of All Words
    [Leetcode] Longest Palindromic Substring
    [Leetcode] Maximum Product Subarray
    [leetcode] Permutation Sequence
    [Leetcode] Simplify Path
    [Leetcode] Minimum Window Substring
    Owin asp.net 脱离 IIS
  • 原文地址:https://www.cnblogs.com/zhiyong-ITNote/p/9484856.html
Copyright © 2020-2023  润新知