.netcore 依赖注入, 跨线程访问控件invoke

一个例子 依赖注入只需要修改注入, 就能改变实现

using Microsoft.Extensions.DependencyInjection;
using System;

namespace DependencyInjectionDemon2
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection services = new ServiceCollection();
            services.AddScoped<Controller>();
            services.AddScoped<ILog, LogImpl>();
            services.AddScoped<IStorage, StorageImp1>();
            //services.AddScoped<IConfig, DBConfigImp1>();
            services.AddScoped<IConfig, ConfigImp1>();

            //注册服务放在BuildServiceProvider之前
            using (var sp = services.BuildServiceProvider())
            {
                var a = sp.GetRequiredService<Controller>();
                a.Test();
            }
        }

        //日志:开始上传
        //向服务器从数据库读取配置的文件名1.txt上传sasasaddfds
        //日志:上传完毕

        //注释掉 DBConfigImp1
        //日志:开始上传
        //向服务器从本地文本读入配置的文件名1.txt上传sasasaddfds
        //日志:上传完毕

        //依赖注入只需要修改注入, 就能改变实现
    }

    class Controller
    {
        private readonly ILog log;
        private readonly IStorage storage;

        public Controller(ILog log, IStorage storage)
        {
            this.log = log;
            this.storage = storage;
        }

        public void Test()
        {
            log.Log("开始上传"); //字符串参数
            storage.Save("sasasaddfds", "1.txt");
            log.Log("上传完毕");
        }
    }

    interface ILog
    {
        public void Log(string msg);
    }

    interface IConfig
    {
        public string GetValue(string name);
    }

    interface IStorage
    {
        public void Save(string content, string name);
    }


    class LogImpl : ILog
    {
        public void Log(string msg)
        {
            Console.WriteLine($"日志:{msg}");
        }
    }

    class ConfigImp1 : IConfig
    {
        public string GetValue(string name)
        {
            return "从本地文本读入配置";
        }
    }

    class DBConfigImp1 : IConfig
    {
        public string GetValue(string name)
        {
            return "从数据库读取配置";
        }
    }

    class StorageImp1 : IStorage
    {
        private readonly IConfig config;
        public StorageImp1(IConfig config)
        {
            this.config = config;
        }
        public void Save(string content, string name)
        {
            string server = config.GetValue("server");
            Console.WriteLine($"向服务器{server}的文件名{name}上传{content}");
        }
    }

}

各种依赖注入的方法

using Microsoft.Extensions.DependencyInjection;
using System;

namespace DependencyInjectionDemon
{
    class Program
    {
        static void Main(string[] arges)
        {
            ServiceCollection services = new ServiceCollection();
            services.AddScoped<ITestService, TestServicelmp1>();//服务的类型, 实现的类型
            //services.AddScoped(typeof(ITestService), typeof(TestServicelmp1));//与上面一样

            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                //TestServicelmp1 ts1 = sp.GetService<ITestService>();
                ITestService ts1 = sp.GetService<ITestService>();
                ts1.Name = "宋江";
                ts1.SayHi();
                Console.WriteLine(ts1.GetType());
            }
        }

        static void Main1(string[] args)
        {
            ServiceCollection services = new ServiceCollection(); //构造容器对象
            services.AddTransient<TestServicelmp1>(); //添加瞬态服务
            using (ServiceProvider sp = services.BuildServiceProvider()) //创建provider 相当于serviceLocator 服务定位器
            {
                //服务定位器
                TestServicelmp1 t = sp.GetService<TestServicelmp1>(); //向Provider要对象
                t.Name = "西门庆";
                

                TestServicelmp1 t1 = sp.GetService<TestServicelmp1>();
                t1.Name = "武大郎";

                t.SayHi();
                t1.SayHi();
                Console.WriteLine("--------------------");
                Console.WriteLine(object.ReferenceEquals(t,t1));

                //I am 西门庆
                //I am 武大郎
                //--------------------
                //False
            }

            services.AddSingleton<TestServicelmp1>(); //添加单例
            using (ServiceProvider sp = services.BuildServiceProvider()) //创建provider 相当于serviceLocator 服务定位器
            {
                //服务定位器
                TestServicelmp1 t = sp.GetService<TestServicelmp1>(); //向Provider要对象
                t.Name = "西门庆";
                
                TestServicelmp1 t1 = sp.GetService<TestServicelmp1>();
                t1.Name = "武大郎";

                t.SayHi();
                t1.SayHi();
                Console.WriteLine("--------------------");
                Console.WriteLine(object.ReferenceEquals(t, t1));
                //I am 武大郎
                //I am 武大郎
                //--------------------
                //True
            }

            services.AddScoped<TestServicelmp1>(); //添加范围对象
            using (ServiceProvider sp = services.BuildServiceProvider()) //创建provider 相当于serviceLocator 服务定位器
            {
                using (IServiceScope scope1 = sp.CreateScope())
                {
                    //在scope中获取Scope相关的对象 scope1.ServiceProvider而不是sp
                    //scope1.ServiceProvider.GetService<TestServicelmp1>();

                    //服务定位器
                    TestServicelmp1 t = scope1.ServiceProvider.GetService<TestServicelmp1>(); //向Provider要对象
                    t.Name = "西门庆";

                    TestServicelmp1 t1 = scope1.ServiceProvider.GetService<TestServicelmp1>();
                    t1.Name = "武大郎";

                    t.SayHi();
                    t1.SayHi();
                    Console.WriteLine("--------------------");
                    Console.WriteLine(object.ReferenceEquals(t, t1));
                    //I am 武大郎
                    //I am 武大郎
                    //--------------------
                    //True
                }
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private CancellationTokenSource cts = new CancellationTokenSource();

        private void btn1_Click(object sender, EventArgs e)
        {
            
            Task.Run(async () =>
            {
                Action<int> action = a => { this.textBox1.Text = a.ToString(); };
                for (int i = 0; i < 10000; i++)
                {
                    await Task.Delay(100);
                    this.textBox1.Invoke(action, i);
                }

            }, cts.Token);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值