You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 2.0 跨项目本地化:Common如何读取WebApi资源文件?

如何让Common项目读取WebApi项目中的资源文件

我之前处理过类似的跨项目资源访问场景,分享几个实用的方案,你可以根据自己的项目结构和需求来选择:

方案1:依赖注入传递资源访问服务(推荐,低耦合)

这是最贴合.NET依赖注入设计思想的方式,能有效降低项目间的耦合度:

  • 第一步,在WebApi项目中定义一个资源读取的接口,比如IResourceReader:
    public interface IResourceReader
    {
        string GetString(string resourceKey);
    }
    
  • 第二步,在WebApi里实现这个接口,直接读取本地的资源文件(假设你的资源文件是WebApiResources.resx):
    public class WebApiResourceReader : IResourceReader
    {
        public string GetString(string resourceKey)
        {
            return WebApiResources.ResourceManager.GetString(resourceKey) ?? string.Empty;
        }
    }
    
  • 第三步,在WebApi的Program.cs中注册这个服务:
    builder.Services.AddScoped<IResourceReader, WebApiResourceReader>();
    
  • 第四步,在Common项目中,给需要读取资源的类注入IResourceReader,通过接口方法获取字符串:
    public class CommonBusinessService
    {
        private readonly IResourceReader _resourceReader;
    
        public CommonBusinessService(IResourceReader resourceReader)
        {
            _resourceReader = resourceReader;
        }
    
        public void ExecuteLogic()
        {
            var tipMessage = _resourceReader.GetString("OperationSuccessTip");
            // 后续业务逻辑
        }
    }
    

方案2:将资源文件设为嵌入资源直接读取

如果不想引入依赖注入,也可以把WebApi的资源文件设置为嵌入资源,让Common直接加载读取:

  • 右键WebApi中的资源文件,在属性面板里设置生成操作为嵌入的资源,自定义工具留空。
  • 在Common项目中,通过程序集加载嵌入的资源:
    public static string GetWebApiResource(string resourceKey)
    {
        // 替换成你的WebApi项目程序集名称
        var webApiAssembly = Assembly.Load("YourWebApiProjectName");
        // 资源文件的完整命名(格式:程序集名.资源文件所在路径.资源文件名)
        var fullResourceName = "YourWebApiProjectName.Properties.WebApiResources";
        var resourceManager = new ResourceManager(fullResourceName, webApiAssembly);
        return resourceManager.GetString(resourceKey) ?? string.Empty;
    }
    

    注意:这种方式耦合度较高,硬编码了程序集和资源名称,后续修改资源位置或程序集名称时需要同步调整代码。

方案3:将资源文件迁移到Common项目(最简洁)

如果这些资源是多个项目共用的,更推荐直接把资源文件移到Common项目中:

  • 将WebApi里的资源文件复制到Common项目,设置生成操作为ResXFileCodeGenerator(会生成强类型的资源访问类)。
  • 之后WebApi和Common项目都可以直接通过强类型类读取资源:
    // WebApi中使用
    var prompt = CommonResources.LoginPrompt;
    // Common中使用
    var prompt = CommonResources.LoginPrompt;
    
    这个方案结构最清晰,完全避免了跨项目读取资源的问题,适合资源属于公共通用场景的情况。

内容的提问来源于stack exchange,提问作者The Eagle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:46:15