【发布时间】:2015-02-16 17:52:31
【问题描述】:
在我们的代码库中,我看到了不同 ServiceStack 服务之间的一些共享(我认为不合适)。我认为这不是一个好主意,因为每个服务的“边界”变得复杂。以“边界”为例,它可以表示数据库连接的边界,我将以数据库连接边界为例来说明我的意思。
例如,如果我有以下两个服务。
[Route("/service-a/", Verbs = "POST")]
public class DtoServiceA : IReturn<IList<string>>
{
}
public class ServiceA : Service //service stack service
{
public ServiceA(Funq.Container container) : base(container)
{
_container = container; //I didn't type the full code
}
public IList<string> Post(DtoServiceA request)
{
//do something that belongs to ServiceA
//then resolve ServiceB and call Post() from ServiceB
Container.Resolve<ServiceB>().Post(new DtoServiceB());
return new List<string>();
}
}
[Route("/service-b/", Verbs = "POST")]
public class DtoServiceB : IReturn<IList<string>>
{
}
public class ServiceB : Service //service stack service
{
public ServiceB(Funq.Container container) : base(container)
{
_container = container; //I didn't type the full code
}
public IList<string> Post(DtoServiceB request)
{
//do something that belongs to ServiceB
return new List<string>();
}
}
假设如果我像这样在 Post 方法中控制数据库连接
public IList<string> Post(DtoServiceA request)
{
//suppose if I control db connection like so
using (var conn = IDbConnectionFactory.Open())
{
//do something that belongs to ServiceA
//then resolve ServiceB and call Post() from ServiceB
Container.Resolve<ServiceB>().Post(new DtoServiceB());
//above line will fail because connection has already been opend by ServiecA.Post()
}
}
public IList<string> Post(DtoServiceB request)
{
//suppose if I control db connection like so
using (var conn = IDbConnectionFactory.Open())
{
}
}
因为数据库连接已经打开,所以显然这不是“共享”服务的好方法。但是我们有一种更复杂的方法来打开数据库连接,基本上它会计算/检测它是否打开,因此不会多次打开连接。但这对我来说是代码味道。
我在其他地方发现人们提出了类似的共享服务方式。我不是 100% 相信这是个好建议。
我可能会做类似下面的事情,并将 using 语句中的代码提取到一个单独的类/类中。
public IList<string> Post(DtoServiceA request)
{
//suppose if I control db connection like so
using (var conn = IDbConnectionFactory.Open())
{
//move code to a searapte "none servicestack service", which
//can be just a normal c# class
//so that the "boundary" is being controlled at service stack level
//and the actual code that does the job is extracted elsewhere
Resolve<NoneServiceStackServiceA>().DoSomething();
Resolve<NoneServiceStackServiceB>().DoSomething();
}
}
public IList<string> Post(DtoServiceB request)
{
//suppose if I control db connection like so
using (var conn = IDbConnectionFactory.Open())
{
//move code to a searapte "none servicestack service", which
//can be just a normal c# class
//so that the "boundary" is being controlled at service stack level
//and the actual code that does the job is extracted elsewhere
Resolve<NoneServiceStackServiceB>().DoSomething();
}
}
欢迎任何建议/建议。谢谢。
【问题讨论】:
标签: c# servicestack inversion-of-control