Wpf之Microsoft.Extensions.DependencyInjection

2021-03-09 10:28

阅读:517

标签:eve   override   make   soft   dir   tab   sig   EOS   read   

参考Autofac.Extras.CommonServiceLocator实现ServiceCollectionServiceLocator
/// 
/// Implementation of the Microsoft CommonServiceLocator.
/// 
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 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();
    }
}
在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()),
                Categories.BindService(ServiceLocator.Current.GetInstance()),
                MovieRpc.BindService(ServiceLocator.Current.GetInstance())},
                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(Configuration.GetSection(nameof(AppSettings)));

        // Service
        container.AddDbContext(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();
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton(new MotionService(100, 5, 10000));

        // VM
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton();
        container.AddSingleton(new LogViewModel());
        container.AddSingleton();

        // 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();
    //        builder.RegisterType();
    //        builder.RegisterType();
    //        builder.RegisterType();
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterInstance(new MotionService(100, 5, 10000)).SingleInstance();

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

    //        // VM
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterType().SingleInstance();
    //        builder.RegisterInstance(new LogViewModel()).SingleInstance();
    //        builder.RegisterType().SingleInstance();
    //    }

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

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

    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

标签:eve   override   make   soft   dir   tab   sig   EOS   read   

原文地址:https://www.cnblogs.com/linxmouse/p/12751085.html


评论


亲,登录后才可以留言!