Wpf之Microsoft.Extensions.DependencyInjection

Posted linxmouse

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("程序执行遇到错误.
详情请查看日志信息.", "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

以上是关于Wpf之Microsoft.Extensions.DependencyInjection的主要内容,如果未能解决你的问题,请参考以下文章

.NET6之MiniAPI(十七):缓存

.net core 基础之读取配置文件

访问 Microsoft.Extensions.Hosting 服务时出现问题。使用 AddPooledDbContextFactory

命名空间Microsoft.Extensions中不存在缓存

解析 Microsoft.Extensions.DependencyInjection 2.x 版本实现

无法从 Microsoft.Extensions.Logging 解析 ILogger