现在的位置: 首页 > 综合 > 正文

使用非ServiceDependency方法获得模块中已注册的服务

2013年06月16日 ⁄ 综合 ⁄ 共 901字 ⁄ 字号 评论关闭

WCSF中注入的服务最终都是存在OB中, 在View, Presenter和Controller中可用通过[ServiceDependency]修饰来引入使用.

通过分析CompositeWeb的源码, 这里给出一种直接获得当前模块中服务的方法, 当然, 一般项目中的模块都能使用[ServiceDependency].

public static object GetInjectService(Type serviceType, IHttpContext context)
{
    object service = null;
    if (context.ApplicationInstance is WebClientApplication)
    {
        WebClientApplication app = (WebClientApplication)context.ApplicationInstance;

        // 获得用来加载模块的服务.
        IModuleContainerLocatorService locatorService = app.RootContainer.Services.Get<IModuleContainerLocatorService>();
        // 获得当前模块中的container.
        CompositionContainer container = locatorService.GetContainer(context.Request.AppRelativeCurrentExecutionFilePath);

        // 从container中获得服务.
        service = container.Services.Get(serviceType);
    }
    return service;
}

若对于当前用户, IHttpContext接口可这样得到:

IHttpContext context = new Microsoft.Practices.CompositeWeb.Web.HttpContext(System.Web.HttpContext.Current)

【上篇】
【下篇】

抱歉!评论已关闭.