你需要实现 IHttpHandlerFactory,跟用 unity 一样。
不会,因为unity也需要实现IHttpHandlerFactory;所以我换了MEF,没想到也是要实现,能否稍微写两句点拨下
@flyjonson: 我给你的连接里面有个完整的实现。
public class SimpleWebHandlerFactory : IHttpHandlerFactory { public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path) { Type type = WebHandlerParser.GetCompiledType(context, virtualPath, path); if (!(typeof(IHttpHandler).IsAssignableFrom(type))) throw new HttpException("Type does not implement IHttpHandler: " + type.FullName); return Activator.CreateInstance(type) as IHttpHandler; } public virtual void ReleaseHandler(IHttpHandler handler) { } } internal class WebHandlerParser : SimpleWebHandlerParser { internal WebHandlerParser(HttpContext context, string virtualPath, string physicalPath) : base(context, virtualPath, physicalPath) { } public static Type GetCompiledType(HttpContext context, string virtualPath, string physicalPath) { WebHandlerParser parser = new WebHandlerParser(context, virtualPath, physicalPath); Type type = parser.GetCompiledTypeFromCache(); if (type != null) return type; else throw new HttpException(string.Format("File '{0}' is not a web handler.", virtualPath)); } protected override string DefaultDirectiveName { get { return "webhandler"; } } } public class ComposableWebHandlerFactory : SimpleWebHandlerFactory { public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path) { IHttpHandler handler = base.GetHandler(context, requestType, virtualPath, path); if (handler != null) { CompositionBatch batch = new CompositionBatch(); batch = BuildUp(batch, handler); ContextualCompositionHost.Container.Compose(batch); } return handler; } private CompositionBatch BuildUp(CompositionBatch batch, IHttpHandler handler) { ComposablePart part = AttributedModelServices.CreatePart(handler); // any imports? if (part.ImportDefinitions.Any()) { if (part.ExportDefinitions.Any()) // exports are not allowed throw new Exception(string.Format("'{0}': Handlers cannot be exportable", handler.GetType().FullName)); batch.AddPart(part); } return batch; } }
@flyjonson: The source code can be downloaded here.
如果你不能读懂他的代码的话,我的建议是你把他的源码下载下来,运行几次,分析下程序的逻辑。
@Launcher: 好的。我先试试,谢谢