洋葱架构
- 内层部分比外层更抽象(内层接口,外层实现)。
- 外层的代码只能调用内层的代码,内层的代码可以通过依赖注入的形式来间接调用外层的代码
简单的例子,引用依赖图
demo
- 接口类库
EmailInfo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Intf
{
public class EmailInfo
{
public string Email { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public EmailInfo(string email,string subject,string body)
{
Email = email;
Subject = subject;
Body = body;
}
}
}
IGenerateMessage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Intf
{
public interface IGenerateMessage
{
public IEnumerable<EmailInfo> GenerateEmail();
}
}
ISendMessage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Intf
{
public interface ISendMessage
{
public Task SendMessageAsync(EmailInfo emailInfo);
}
}
Mybusiness 这是实现业务的地方,注入两个接口,一个是获取数据,一个是发送信息,实现均在控制台工程实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Intf
{
public class Mybusiness
{
public IGenerateMessage GenerateMessage { get; set; }
public ISendMessage SendMessage { get; set; }
public Mybusiness(IGenerateMessage generateMessage, ISendMessage sendMessage)
{
GenerateMessage = generateMessage;
SendMessage = sendMessage;
}
public async Task DoIt()
{
var items = GenerateMessage.GenerateEmail();
foreach (var item in items)
{
await SendMessage.SendMessageAsync(item);
await Task.Delay(1000);
}
}
}
}
- 控制台工程
GenerateMessage
using Intf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Onion
{
internal class GenerateMessage : IGenerateMessage
{
public IEnumerable<EmailInfo> GenerateEmail()
{
for (int i = 0; i < 5; i++)
{
yield return new EmailInfo("1.com", "你好", "你好");
}
}
}
}
MyEmailSender
using Intf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Onion
{
internal class MyEmailSender : ISendMessage
{
public Task SendMessageAsync(EmailInfo emailInfo)
{
Console.WriteLine($"{emailInfo.Email} {emailInfo.Subject} {emailInfo.Body}");
return Task.CompletedTask;
}
}
}
program
//依赖注入
using Intf; //类库名称
using Microsoft.Extensions.DependencyInjection;//
using Onion;//控制台工程名称
ServiceCollection service = new ServiceCollection();
service.AddScoped<IGenerateMessage, GenerateMessage>();
service.AddScoped<ISendMessage, MyEmailSender>();
service.AddScoped<Mybusiness>();
var sp = service.BuildServiceProvider();
Mybusiness business = sp.GetRequiredService<Mybusiness>();
business.DoIt();
Console.WriteLine("Hello, World!");