2

我正在尝试创建一个必须声明为静态类的 MVC html 帮助程序扩展,如下所示:

public static class PhotoExtension
{
    public static IPhotoService PhotoService { get; set; }
    public static IGalleryService GalleryService { get; set; }

    public static MvcHtmlString Photo(this HtmlHelper helper, int photoId, string typeName)
    {
         //[LOGIC GOES HERE]
         return new MvcHtmlString(..some resulting Html...);
    }
}

现在,我想在该Photo()方法中使用 IPhotoService 和 IGalleryService。到目前为止,我发现如何在 AppHost.Configure() 中注入这些服务的唯一方法:

PhotoExtension.PhotoService = container.Resolve<IPhotoService>();
PhotoExtension.GalleryService = container.Resolve<IGalleryService>();

这行得通,尽管我很好奇是否有更好的方法来实现这一点。

IPhotoService和都IGalleryService以标准方式注册在AppHost.Configure().

谢谢,安东宁

4

1 回答 1

2

更容易阅读/遵循,将它们连接到静态构造函数中?

using ServiceStack.WebHost.Endpoints;

public static class PhotoExtension
{
    public static IPhotoService PhotoService { get; set; }
    public static IGalleryService GalleryService { get; set; }

    static PhotoExtension()
    {
        PhotoService = EndpointHost.AppHost.TryResolve<IPhotoService>();
        GalleryService  = EndpointHost.AppHost.TryResolve<IGalleryService>();
    }

    public static MvcHtmlString Photo(this HtmlHelper helper, int photoId, string typeName)
    {
     //[LOGIC GOES HERE]
     return new MvcHtmlString(..some resulting Html...);
    }
}
于 2013-05-30T22:07:42.753 回答