Wpf之Microsoft.Extensions.DependencyInjection

参考Autofac.Extras.CommonServiceLocator实现ServiceCollectionServiceLocator
/// <summary>
/// Implementation of the Microsoft CommonServiceLocator.
/// </summary>
public class ServiceCollectionServiceLocator: ServiceLocatorImplBase
{
    private readonly IServiceProvider services;

    public ServiceCollectionServiceLocator(IServiceProvider services)
    {
        this.services = services ?? throw new ArgumentNullException();
    }

    protected override object DoGetInstance(Type serviceType, string key)
    {
        if (serviceType == null)
        {
            throw new ArgumentNullException(nameof(serviceType));
        }

        return services.GetRequiredService(serviceType);
    }

    protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
    {
        if (serviceType == null)
        {
            throw new ArgumentNullException(nameof(serviceType));
        }

        var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);

        var instance = services.GetServices(enumerableType);
        return ((IEnumerable)instance).Cast<object>();
    }
}
在Mvvmlight中使用Microsoft.Extensions.DependencyInjection
public class AppLocator : ViewModelBase
{
    public IConfiguration Configuration { get; private set; }

    public AppLocator()
    {
        #region Microsoft.Extensions.DependencyInjection
        Configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", false, true)
            .Build();

        var provider = new ServiceCollectionServiceLocator(Configure());
        ServiceLocator.SetLocatorProvider(() => provider);
        #endregion

        #region AutoFac
        // Set the service locator to an AutofacServiceLocator.
        //var provider = new AutofacServiceLocator(Configure());
        //ServiceLocator.SetLocatorProvider(() => provider);
        #endregion

        #region gRpc
        try
        {
            var server = new Server()
            {
                Services = {
                Greeter.BindService(ServiceLocator.Current.GetInstance<GreeterService>()),
                Categories.BindService(ServiceLocator.Current.GetInstance<CategoryService>()),
                MovieRpc.BindService(ServiceLocator.Current.GetInstance<MovieService>())},
                Ports = { new ServerPort("192.168.31.37", 19840, ServerCredentials.Insecure) }
            };
            server.Start();
        }
        catch (Exception ex)
        {
            LogHelper.Error(ex.Message);
            MessageBox.Show("程序执行遇到错误.\n详情请查看日志信息.", "gRpc",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
        #endregion
    }

    private IServiceProvider Configure()
    {
        var container = new ServiceCollection();

        // Configuration
        container.Configure<AppSettings>(Configuration.GetSection(nameof(AppSettings)));

        // Service
        container.AddDbContext<MyContext>(options =>
            {
                options.UseSqlite("Data Source=stk.db3");
                options.UseLoggerFactory(LoggerFactory.Create(builder =>
                {
                    builder.AddFilter((category, level) =>
                        category == DbLoggerCategory.Database.Command.Name
                        && level == LogLevel.Information);
                    builder.AddConsole();
                }));
            });
        container.AddSingleton<GreeterService>();
        container.AddSingleton<CategoryService>();
        container.AddSingleton<MovieService>();
        container.AddSingleton<StereoscopicPlayer>();
        container.AddSingleton(new MotionService(100, 5, 10000));

        // VM
        container.AddSingleton<MainViewModel>();
        container.AddSingleton<CategoryViewModel>();
        container.AddSingleton<MovieViewModel>();
        container.AddSingleton<PlayTestViewModel>();
        container.AddSingleton<PlayRecordViewModel>();
        container.AddSingleton(new LogViewModel());
        container.AddSingleton<PlatformTestViewModel>();

        // Perform registrations and build the container.
        return container.BuildServiceProvider();
    }

    #region AutoFac Configure
    //private IContainer Configure()
    //{
    //    var builder = new ContainerBuilder();
    //    if (IsInDesignModeStatic)
    //    {

    //    }
    //    else
    //    {
    //        // Service
    //        builder.RegisterType<MyContext>();
    //        builder.RegisterType<GreeterService>();
    //        builder.RegisterType<CategoryService>();
    //        builder.RegisterType<MovieService>();
    //        builder.RegisterType<StereoscopicPlayer>().SingleInstance();
    //        builder.RegisterInstance(new MotionService(100, 5, 10000)).SingleInstance();

    //        // Settings
    //        builder.RegisterInstance(Configuration.GetSection(nameof(AppSettings))).SingleInstance();

    //        // VM
    //        builder.RegisterType<MainViewModel>().SingleInstance();
    //        builder.RegisterType<CategoryViewModel>().SingleInstance();
    //        builder.RegisterType<MovieViewModel>().SingleInstance();
    //        builder.RegisterType<PlayTestViewModel>().SingleInstance();
    //        builder.RegisterType<PlayRecordViewModel>().SingleInstance();
    //        builder.RegisterInstance(new LogViewModel()).SingleInstance();
    //        builder.RegisterType<PlatformTestViewModel>().SingleInstance();
    //    }

    //    // Perform registrations and build the container.
    //    return builder.Build();
    //} 
    #endregion

    // Resolve VM
    public MainViewModel Main => ServiceLocator.Current.GetInstance<MainViewModel>();
    public CategoryViewModel Category => ServiceLocator.Current.GetInstance<CategoryViewModel>();
    public MovieViewModel Movie => ServiceLocator.Current.GetInstance<MovieViewModel>();
    public PlayTestViewModel PlayTest => ServiceLocator.Current.GetInstance<PlayTestViewModel>();
    public PlayRecordViewModel PlayRecord => ServiceLocator.Current.GetInstance<PlayRecordViewModel>();
    public LogViewModel Log => ServiceLocator.Current.GetInstance<LogViewModel>();
    public PlatformTestViewModel PlatformTest => ServiceLocator.Current.GetInstance<PlatformTestViewModel>();

    public override void Cleanup()
    {
        // TODO Clear the ViewModels
    }
}
使用 HttpClientFactory
...
container.AddHttpClient();
...
var client = _httpClientFactory.CreateClient();
var html = await client.GetStringAsync("http://www.baidu.com");
参考资料

https://www.cnblogs.com/hippieZhou/p/10637348.html

上一篇:Visual Studio Code 之 必用 Extensions


下一篇:scrapy专题(五):自定义扩展