简体   繁体   English

C# 包命名空间

[英]C# Bundle Namespaces

I have written a C#-Solution which includes many different projects.我编写了一个 C#-Solution,其中包括许多不同的项目。 As this soltion acts as a backend, I'd like to write an API for it.由于此解决方案充当后端,因此我想为其编写 API。 The problem is that there is a relatively big amount of namespaces that the client would have to add in order to get access to necessary interfaces and classes.问题是客户端必须添加相对大量的命名空间才能访问必要的接口和类。 Is there a way to "bundle" namespaces into one a single namespace (or at least fewer namespaces) so that the Client does not have to add that many using-directives or do I have to completely restructure my backend?有没有办法将命名空间“捆绑”到一个命名空间(或至少更少的命名空间)中,这样客户端就不必添加那么多 using 指令,或者我是否必须完全重组我的后端?

Thanks alot.非常感谢。

Assuming you mean create an ASP.NET WebApi application then the namespaces shouldn't matter.假设您的意思是创建一个 ASP.NET WebApi 应用程序,那么命名空间应该无关紧要。 Any consuming application will receive the data as JSON without namespaces.任何消费应用程序都将接收数据作为没有命名空间的 JSON。

You could consider using a tool like Swagger which acts as a cross platform auto-documenting api tool.您可以考虑使用像Swagger这样的工具作为跨平台自动记录 api 工具。 From a .net point of view there are two popular libraries NSwag and Swashbuckle which help get you started.从 .net 的角度来看,有两个流行的库NSwagSwashbuckle可以帮助您入门。 NSwag also includes tools for creating client classes by inspecting the swagger.json file like the old WSDL definitions. NSwag 还包括通过检查swagger.json文件(如旧的 WSDL 定义)来创建客户端类的工具。

As long as your JSON objects have the same property names, any client will happily deserialize them into their own namespaces classes.只要您的 JSON 对象具有相同的属性名称,任何客户端都会很乐意将它们反序列化为自己的命名空间类。

The other option which might be cleaner if you are only consuming this api internally would be to reproduce all the classes you wish to output via the api in a separate class library.如果您仅在内部使用此 api,则另一个可能更清晰的选项是在单独的类库中重现您希望通过 api 输出的所有类。 The api is then responsible for mapping between the existing namespaces/classes and the new ones.然后 api 负责在现有命名空间/类和新命名空间/类之间进行映射。 Tools like Automapper can help a lot with this. Automapper 等工具对此有很大帮助。 It has the added advantage that you can customise the mapping so that only exactly the data that is required is emitted by the api, and all extraneous data is not.它有一个好处,你可以自定义映射,使只有正是需要通过API发出的数据,所有无关的数据是没有的。

This class library could then be shared between applications either as a project reference, dll or (best if you have the right setup) a NuGet package.然后可以在应用程序之间共享此类库,作为项目引用、dll 或(如果设置正确,则最好)NuGet 包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM