.net core di 一对多的方式

using Microsoft.Extensions.DependencyInjection;
using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello DI IOC!");
            var provider = new ServiceCollection()
                .AddSingleton<MessagePrinter>()
                //.AddSingleton<IWriter, ConsoleWriter>()
                .AddSingleton<ConsoleWriter>()
                .AddSingleton<TextWriter>()
                //简单工厂模式,针对不同的 key 来获取指定的对象实例
                .AddSingleton(factory => 
                {
                    Func<string, IWriter> accesor = (key) =>
                    {
                        if (key.Equals("Console")) return factory.GetRequiredService<ConsoleWriter>();
                        else if (key.Equals("Text")) return factory.GetRequiredService<TextWriter>();
                        else throw new ArgumentException($"Not Support : {key}");
                    };
                    return accesor;
                })
                .BuildServiceProvider(validateScopes: false);
            var consoleWriter = provider.GetRequiredService<MessagePrinter>();
            consoleWriter.WriteLine();
        }
    }
    public interface IWriter
    {
        void WriteLine();
    }
    public class ConsoleWriter : IWriter
    {
        public void WriteLine()
        {
            Console.WriteLine("ConsoleWriter");
        }
    }
    public class TextWriter : IWriter
    {
        public void WriteLine()
        {
            Console.WriteLine("TextWriter");
        }
    }

    public class MessagePrinter
    {
        private readonly Func<string,IWriter> _writers;
        public MessagePrinter(Func<string, IWriter> writers)
        {
            _writers = writers;
        }

        public void WriteLine()
        {
            _writers("Console").WriteLine();
            _writers("Text").WriteLine();
        }
    }



}

 

posted @ 2024-02-22 15:32  每天学习一点哈哈哈  阅读(18)  评论(0编辑  收藏  举报