首页 技术交流 net webapi依赖注入autofac使用MediatR中介者模式进行开发教程 正文

net webapi依赖注入autofac使用MediatR中介者模式进行开发教程

发布日期:2022年03月28日 17:17        阅读次数:243

        首先需要安装nuget包MediatR。因为我这是老的项目版本比较低是netframework4.5的,需要安装对应版本的MediatR.


autofac注册:(MediatR官方教程:https://github.com/jbogard/MediatR/wiki

 var builder = new ContainerBuilder();
            builder.RegisterType<WxTemplate>().As<IWxTemplate>();
            
            builder.RegisterApiControllers(Assembly.GetAssembly(typeof(u_NewsPageController)));
            // Mediator itself
            builder
                .RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            // request & notification handlers
            builder.Register<ServiceFactory>(context =>
            {
                var c = context.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });

            // finally register our custom code (individually, or via assembly scanning)
            // - requests & handlers as transient, i.e. InstancePerDependency()
            // - pre/post-processors as scoped/per-request, i.e. InstancePerLifetimeScope()
            // - behaviors as transient, i.e. InstancePerDependency()
            //builder.RegisterAssemblyTypes(typeof(MyType).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan
            //注册自定义的handle
           builder.RegisterType<WxTemplateSendCommandHandle>().AsImplementedInterfaces().InstancePerDependency();        
            config.DependencyResolver = new AutofacWebApiDependencyResolver(builder.Build());

  WxTemplateSendCommand和WxTemplateSendCommandHandle类:

using LTSW.GeneralMethod;
using MediatR;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace LTSW.LightWeb.WechatTemplate
{
    public class WxTemplateSendCommand : IRequest<string>
    {
        public int NewsId { get; set; }
    }
    public class WxTemplateSendCommandHandle : IRequestHandler<WxTemplateSendCommand, string>
    {
        private readonly IWxTemplate _wxTemplate;
        public WxTemplateSendCommandHandle(IWxTemplate wxTemplate)
        {
            _wxTemplate = wxTemplate;
        }
        public async Task<string> Handle(WxTemplateSendCommand request, CancellationToken cancellationToken)
        {
            //这里写自己的业务逻辑 可以用到传递的参数 request.NewsId
            return await Task.FromResult("ok");
        }
    }
}

   控制器:

public class u_NewsPageController : BaseApiController
    {
         private readonly IMediator _mediator;
         
        public u_NewsPageController(IMediator mediator)
        {
            _mediator = mediator;
        }
         public object WechatPush()
        {
            int id = int.Parse(MyRequest["id"] ?? "0");
            _mediator.Send(new WxTemplateSendCommand { NewsId = id });
            
            return OutputJson(new { DATA = "成功", ErrCode= "SUCCESS" });
        }
        }

                            

评论:

共 0 页 0 条记录,当前为第 1 页