1

私が取り組んでいるかなり小さな Web サイトがあり、HTML で絶対パスを相対パスに変換する必要があるところまで来ました。私は IoC に AutoFac を使用しており、プロジェクト全体に web.config アプリ設定を挿入するラッパーを作成しましたが、このビットで壁にぶつかりました:

「ContentServerPath」と呼ばれる構成値があり、ラッパーが引き継ぎます。

public interface IConfigurationWrapper
{
    string ContentServerPath { get; }
}

と私の実装(かなり簡単):

public ConfigurationWrapper()
        : this(ConfigurationManager.AppSettings, ConfigurationManager.ConnectionStrings)
    {
    }


    internal ConfigurationWrapper(NameValueCollection appSettings, ConnectionStringSettingsCollection connectionStrings)
    {
        ContentServerPath = appSettings["ContentServerPath"];
    }

私の _layout.cshtml ページは、サイトの開発中に、最初はローカル スタイルシートと jquery を使用するようにコーディングされています。

<link rel="stylesheet" type="text/css" href="~/assets/styles/site.css" />

私が望んでいた最終的な出力は、html行を次の行に沿ったものに置き換えることでした:

<link rel="stylesheet" type="text/css" href="@Html.GetContentPath("assets/styles/site.css")" />

ただし、拡張メソッドを呼び出すときに IConfigurationWrapper を静的クラスに挿入できないという事実により、それは恐ろしい作業であることが証明されています。

私の最初の考えは、

public static MvcHtmlString GetContentPath(this HtmlHelper htmlHelper, string relativeContentPath)
    {
        return string.Format("{0}/{1}", _configuration.ContentServerPath, relativeContentPath);
    }

しかし、繰り返しになりますが、構成ラッパーを静的メソッドに挿入することはできません。

補足として、コンテンツ パスを web.config に入れた理由は、いくつかの異なるテスト環境があり、それぞれがコンテンツに対して独自の構成値を必要とするためです。コードをデプロイする前に変更を取得し、それに応じて構成を変更するために、ビルドサーバーの xdt 変換に依存しています。

誰かが前にこのようなことに遭遇し、良い解決策を持っていますか? 前もって感謝します!

4

2 に答える 2

0

そのため、さらに数時間調査した後、拡張機能で依存関係リゾルバーを使用して、探していた構成値を取得しました。

public static class HtmlHelperExtensions
{
    public static MvcHtmlString GetContentPath(this HtmlHelper htmlHelper, string relativeContentPath)
    {
        return GetContentPath(relativeContentPath, AutofacDependencyResolver.Current.ApplicationContainer.Resolve<IConfigurationWrapper>());
    }

    internal static MvcHtmlString GetContentPath(string relativeContentPath, IConfigurationWrapper configuration)
    {
        return new MvcHtmlString(string.Format("{0}/{1}", configuration.ContentServerPath, relativeContentPath););
    }
}

うまくいけば、これは少なくとも他の誰かが道を進むのに役立ちます!

-トロギー

于 2013-10-01T05:22:45.053 に答える