Skip to main content
 首页 » 编程设计

c#之一个坚实而有组织的架构应该如何

2024年02月20日15mq0036

在工作中,我们要重写一个旧的应用程序,我被告知要获得一些关于如何做到这一点的想法。

我的想法是:

由于应用程序将主要是一个网站,所以我会使用 MVC。带有用于 DI 和 IoC 的 POCO 实体的 EF。用于 Web 应用程序和其他客户端将使用的服务的 WCF。

到目前为止,架构应该是这样的: - 演示.Web - 演示.Entities - 演示服务

现在我的架构是这样的:

命名空间 Demo.Entities

// IEntity.cs 
public interface IEntity { } 
 
//User.cs 
public virtual long UserId { get; private set; } 
public virtual string Name { get; private set; } 
 
public User() { } 
public User(long userId, string name) 
{ 
    UserId = userId; 
    Name = name; 
} 

命名空间演示服务

// IService.cs 
public interface IService<T> : IDisposable where T : IEntity 
{ 
    List<T> GetList(); 
} 
 
// UserService.cs 
public class UserService : IService<User> 
{ 
    public List<User> GetList() 
    { 
        return new List<User>(); // Simplicity 
    } 
 
    public void Dispose() { } 
} 

当我需要使用它时,我会这样做:

using(IService<User> service = new UserService()) 
{ 
    var q = service.GetList(); 
} 

至于 MVC,我将使用 Demo.Models 中的模型,如果需要实际模型,我会将它们链接到我的 MVC 应用程序的模型文件夹中,但现在 MVC 是我最后关心的问题。

到目前为止,我已经检测到一个问题,如果不实例化指定的服务,我将无法查询多个实体。从好的方面来说,我可以完全控制我的数据的内容和处理方式。

实际问题

如果有的话,谁能告诉我支持这些功能的任何架构设计?

请您参考如下方法:

我是 SOLID 架构原则的忠实粉丝 here和 here .在您做出最终决定之前,它们值得检查和使用。 DotNetJunkie 还将在不久的将来发布另一篇关于如何将这些模式与 WCF 结合使用的博客文章。他描述的接口(interface)和模式已充分解耦,可以将它们与 EF 或 NHibernate 一起使用。

我在您的帖子中看到的一个问题是 IEntity 接口(interface)。我认为您不需要为您的基实体提供接口(interface),通常一个抽象基类就足够了(即使用 Layer Supertype 模式)。我从未找到让所有实体都订阅单一接口(interface)契约的理由。

我在您的示例中也没有看到任何依赖项注入(inject)。任何使用 using(IService<User> ctx = new UserService()) 的代码依赖于接口(interface)和实现。您希望您的 MVC 或其他客户端代码仅对接口(interface)产生硬依赖,并通过您的反转控制容器解析/注入(inject)具体实现。这是 the Onion Architecture that trailmax posted about 中常见的模式.

我非常喜欢您拥有项目“三脚架”的想法。不过,尽量不要让解决方案中的项目数超过 5 个左右(不包括单元测试项目,那些不算数)。

So far I've detected one issue, I won't be able to query multiple entities without instantiating the specified service. On the bright side I have full control of what and how my data is being handled.

同样,这些问题可以通过阅读和采用 ICommandHandler 来解决。和 IQueryHandler/IQueryProcessor我上面提到的文章中描述的模式。您根本不必实例化任何服务。您只需构造函数注入(inject) IQueryProcessor或 ICommandHandler<TCommand>进入你的 Controller ,并让 IoC 容器提供实现。如果您有一个需要查询多个实体的操作,您只需在查询的 Handle 中访问 EF 或 NHibernate 即可。方法。

这是我使用这些模式的项目之一的示例:

MyApp.Domain.csproj

包含所有实体以及 DotNetJunkie 接口(interface)和命令 + 查询实现的类库。这对 Entity Framework 或任何其他项目不依赖。

MyApp.Impl.csproj

包含接口(interface)实现的类库,以及 EF DbContext 和 IoC 容器。这依赖于 Domain 项目以及 EF、IoC 库等。

MyApp.Mvc.csproj

MVC 项目依赖于其他两个项目。

这是洋葱架构的一个非常基本的例子。