您的位置:首页 > 大数据 > 人工智能

eShopOnContainers 学习之--Ordering的中介者模式

2017-12-13 18:21 806 查看

前言

学习目的:

MediatR是什么?

为什么他要用MediatR?

怎么使用MediatR?

MediatR是什么?

MediatR 官方网站:https://github.com/jbogard/MediatR

官方介绍:

Simple mediator implementation in .NET

什么是【mediator/中介者模式】?

PS:其实之前学习23种设计模式中学过他,用的少就快忘记完了。以前碰到的类似问题基本上都用观察者模式去解决(特别是出了ReactiveX 出现了以后),没有考虑用使用这种设计模式。

这儿有个详细解释:23种设计模式(7):中介者模式

直接抄下他的优点:

适当地使用中介者模式可以避免同事类之间的过度耦合,使得各同事类之间可以相对独立地使用。

使用中介者模式可以将对象间一对多的关联转变为一对一的关联,使对象间的关系易于理解和维护。

使用中介者模式可以将对象的行为和协作进行抽象,能够比较灵活的处理对象间的相互作用。

为什么他要用MediatR?

在 Ordering.API 中主要干了下面的事情:

数据校验;

实现队列请求(Request 、Order);

与 Dapper 配合代替 EF;

同事类交互(Paid、Buyer、Order State)

怎么使用MediatR?

注册:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
//configure autofac

var container = new ContainerBuilder();
container.Populate(services);

container.RegisterModule(new MediatorModule()); // 把 MediatR 注入到 Autofac 中
container.RegisterModule(new ApplicationModule(Configuration["ConnectionString"])); // 注册本项目用到的同事类和 handler,因为要使用 Dapper,所以把数据库连接字符串传进去了。

return new AutofacServiceProvider(container.Build());
}


MediatorModule:

public class MediatorModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly)
.AsImplementedInterfaces();

// Register all the Command classes (they implement IAsyncRequestHandler) in assembly holding the Commands
builder.RegisterAssemblyTypes(typeof(CreateOrderCommand).GetTypeInfo().Assembly)
.AsClosedTypesOf(typeof(IAsyncRequestHandler<,>));

// Register the DomainEventHandler classes (they implement IAsyncNotificationHandler<>) in assembly holding the Domain Events
builder.RegisterAssemblyTypes(typeof(ValidateOrAddBuyerAggregateWhenOrderStartedDomainEventHandler).GetTypeInfo().Assembly)
.AsClosedTypesOf(typeof(IAsyncNotificationHandler<>));

// Register the Command's Validators (Validators based on FluentValidation library)
builder
.RegisterAssemblyTypes(typeof(CreateOrderCommandValidator).GetTypeInfo().Assembly)
.Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
.AsImplementedInterfaces();

builder.Register<SingleInstanceFactory>(context =>
{
var componentContext = context.Resolve<IComponentContext>();
return t => { object o; return componentContext.TryResolve(t, out o) ? o : null; };
});

builder.Register<MultiInstanceFactory>(context =>
{
var componentContext = context.Resolve<IComponentContext>();

return t =>
{
var resolved = (IEnumerable<object>)componentContext.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
return resolved;
};
});

builder.RegisterGeneric(typeof(LoggingBehavior<,>)).As(typeof(IPipelineBehavior<,>));
builder.RegisterGeneric(typeof(ValidatorBehavior<,>)).As(typeof(IPipelineBehavior<,>));

}
}


看注释就能看明白,后续就不贴代码。

待续,抽时间用 MediatR 写个项目。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net net-core 设计模式