【发布时间】:2017-07-24 08:33:18
【问题描述】:
我正在关注洋葱架构,其引导程序部分是使用 Autofac 构建的。
架构如下:
- 核心
- DependencyInjection(Autofac 在这里)
- 服务
- 演示文稿 (MVC 5)
- 测试
我需要一些 WebForm.aspx 页面来显示我的报告。所以我按照给出的链接将 WebForms 与 Autofac 集成的说明进行操作:http://docs.autofac.org/en/latest/integration/webforms.html
这是来自 DependencyInjection 的代码:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace DependencyInjection.App_Start
{
public class IocConfig : IContainerProviderAccessor
{
// Provider that holds the application container.
static IContainerProvider _containerProvider;
// Instance property that will be used by Autofac HttpModules
// to resolve and inject dependencies.
public IContainerProvider ContainerProvider
{
get { return _containerProvider; }
}
public static void RegisterDependencies()
{
// Build up your application container and register your dependencies.
var builder = new ContainerBuilder();
// Register your MVC controllers. (MvcApplication is the name of
// the class in Global.asax.)
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider();
builder.RegisterType<MyService().As<IMyService().InstancePerRequest();
// Once you're done registering things, set the container
// provider up with your registrations.
_containerProvider = new ContainerProvider(container);
}
}
}
在 DependencyInjection 的 App.Config 中,我添加了:
<system.web>
<httpModules>
<add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
<add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" preCondition="managedHandler"/>
<add name="PropertyInjection" type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web" preCondition="managedHandler"/>
</modules>
</system.webServer>
仍然无法正常工作。 MyService 仍然是null。当我将 App.Config 设置添加到我的 Presentation 的 Web.Config 中时,出现以下错误:
此模块需要 HttpApplication(全局应用程序 类)实现 IContainerProviderAccessor
【问题讨论】:
标签: asp.net .net webforms autofac onion-architecture