.net8webapi:
public interface ITestKeyService
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Test1KeyService : ITestKeyService
{
public int Id { get; set; } = 1;
public string Name { get; set; } = "Name1";
}
public class Test2KeyService : ITestKeyService
{
public int Id { get; set; } = 2;
public string Name { get; set; } = "Name2";
}
builder.Services.AddKeyedSingleton<ITestKeyService, Test1KeyService>("ServiceA");
builder.Services.AddKeyedSingleton<ITestKeyService, Test2KeyService>("ServiceB");
[Route("api/private/v1/[controller]/[action]")]
[ApiController]
[EnableCors("any")]
public class TestKeyController : ControllerBase
{
private readonly ITestKeyService service1;
private readonly ITestKeyService service2;
public TestKeyController([FromKeyedServices("ServiceA")] ITestKeyService service1, [FromKeyedServices("ServiceB")] ITestKeyService service2)
{
this.service1 = service1;
this.service2 = service2;
}
[HttpGet]
public ActionResult<Dictionary<string, string>> MyTestKey()
{
Dictionary<string, string> dic = new();
dic["服务1的名字"] = service1.Name;
dic["服务2的名字"] = service2.Name;
return dic;
}
}
结果:
在prism 8.0/9.0 中 :
public partial class App : PrismApplication
{
protected override Window CreateShell() => null;
protected override void OnInitialized()
{
//从容器当中获取MainView的实例对象
var container = ContainerLocator.Container;
var shell = container.Resolve<object>("MainView");
if (shell is Window view)
{
//更新Prism注册区域信息
var regionManager = container.Resolve<IRegionManager>();
RegionManager.SetRegionManager(view, regionManager);
RegionManager.UpdateRegions();
//调用首页的INavigationAware 接口做一个初始化操作
if (view.DataContext is INavigationAware navigationAware)
{
navigationAware.OnNavigatedTo(null);
//呈现首页
App.Current.MainWindow = view;
}
}
base.OnInitialized();
}
protected override void RegisterTypes(IContainerRegistry services)
{
//模板匹配服务
services.Register<ITemplateMatchService, ShapeModelService>(nameof(TempalteMatchType.ShapeModel));
services.Register<ITemplateMatchService, NccModelService>(nameof(TempalteMatchType.NccModel));
services.Register<ITemplateMatchService, LocalDeformableService>(nameof(TempalteMatchType.LocalDeformable));
}
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
moduleCatalog.AddModule<TemplateMatchModule>();
base.ConfigureModuleCatalog(moduleCatalog);
}
}
取出:
internal class NccViewModel : NavigationViewModel
{
public ITemplateMatchService MatchService { get; set; }
public NccViewModel()
{
MatchService = ContainerLocator.Current.Resolve<ITemplateMatchService>(nameof(TempalteMatchType.NccModel));
}
}
9.0 Prism的注册方法:
using DryIoc.Microsoft.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using net8wpf.Cad;
using net8wpf.Cad.Utils;
using net8wpf.Device;
using net8Wpf.Core.Data;
using net8Wpf.Core.Data.Yanji;
using net8Wpf.Core.Data.Yanji.Interface;
using net8Wpf.MyLiveChart;
using net8Wpf.MyLiveChart.Service;
using net8Wpf.Service;
using net8Wpf.Share.Communication.MyPlc.MySiemens;
using net8Wpf.Share.Models;
using net8Wpf.Share.RestSharp;
using net8Wpf.ViewModels;
using net8Wpf.Views;
using RestSharp;
using Serilog;
using Serilog.Formatting.Json;
using System.Windows;
namespace net8Wpf
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
protected override Window CreateShell() => null;
protected override IContainerExtension CreateContainerExtension()
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
serviceCollection.AddLogging(logbuilder =>
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console(new JsonFormatter())
.WriteTo.File(
new JsonFormatter(),
@"D:\serialLog\log-.txt",
rollingInterval: RollingInterval.Day
)
.CreateLogger();
logbuilder.AddSerilog();
});
//var a = SerilogServiceCollectionExtensions.AddSerilog(serviceCollection);
return new DryIocContainerExtension(
new Container(CreateContainerRules()).WithDependencyInjectionAdapter(
serviceCollection
)
);
}
protected override void RegisterTypes(IContainerRegistry services)
{
//services.RegisterAssembly(Assembly.GetExecutingAssembly());
services.RegisterSingleton<MyData>();
services.RegisterSingleton<ApiData>();
services.RegisterSingleton<SelfData>();
services.RegisterSingleton<ChartService>();
services.RegisterSingleton<IS7ConnService, S7ConnService>();
services.RegisterSingleton<IDeviceService, DeviceServiceImpl>();
services.RegisterSingleton<IAddGrahService, AddGrahService>();
services.RegisterSingleton<RestClient>(sp => new RestClient("http://localhost:8889"));
//services.Register<MyData>();
services.RegisterForNavigation<MainView, MainViewModel>();
services.RegisterForNavigation<SettingView, SettingViewModel>();
services.RegisterSingleton<INavigationMenuService, NavigationMenuService>();
services.RegisterForNavigation<DashboardView, DashboardViewModel>();
services
.GetContainer()
.Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
services
.GetContainer()
.RegisterInstance(@"http://localhost:8889/", serviceKey: "webUrl");
}
protected override void OnInitialized()
{
var container = ContainerLocator.Container;
var shell = container.Resolve<object>("MainView");
if (shell is Window view)
{
var regionManager = container.Resolve<IRegionManager>();
// 将 RegionManager 实例关联到 myContentControl 控件
RegionManager.SetRegionManager(view, regionManager);
//强制更新所有已注册的区域(Regions)
RegionManager.UpdateRegions();
//检查view的数据上下文(DataContext)是否实现了INavigationAware接口。如果是,则调用OnNavigatedTo方法,并设置应用程序的主窗口为view
if (view.DataContext is INavigationAware navigationAware)
{
navigationAware.OnNavigatedTo(null);
App.Current.MainWindow = view;
}
}
base.OnInitialized();
}
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
moduleCatalog.AddModule<MyLiveChartModule>();
moduleCatalog.AddModule<DeviceModule>();
moduleCatalog.AddModule<MyCadModule>();
base.ConfigureModuleCatalog(moduleCatalog);
}
}
}
异步编程及其取消:
CancellationTokenSource cts = new();
try
{
var a = await helper
.Db.Queryable<Circle2Impl>()
.ToListAsync(cts.Token)
.WaitAsync(TimeSpan.FromSeconds(2));
}
catch (TimeoutException ex)
{
cts.Cancel();
}
finally
{
cts.Cancel();
}