1

application_start()我有以下代码。创建帐户控制器时,我收到无参数构造函数错误。AccountController 没有无参数构造函数。似乎不再配置autofac?

帐户控制器预期以下内容。

public AccountController(IFlexMembershipProvider membership, IFlexOAuthProvider openAuth)

我不确定为什么 autofac 没有注入依赖项?

var builder = new ContainerBuilder();

builder.RegisterType<DataContext>()
    .As<IRepository>()
    .As<DbContext>().InstancePerLifetimeScope();

builder.RegisterType<FlexMembershipProvider>().As<IFlexMembershipProvider>();
builder.RegisterType<FlexMembershipProvider>().As<IFlexOAuthProvider>();
builder.RegisterType<FlexRoleProvider>().As<IFlexRoleProvider>();

builder.RegisterType<UserStorage>().As<IFlexUserStore>().InstancePerLifetimeScope();
builder.RegisterType<RoleStorage>().As<IFlexRoleStore>().InstancePerLifetimeScope();
builder.RegisterType<DefaultSecurityEncoder>().As<ISecurityEncoder>().SingleInstance();
builder.RegisterType<AspnetEnvironment>().As<IApplicationEnvironment>();
builder.RegisterType<InvestorService>().As<IInvestorService>();
builder.RegisterType<InvestmentService>().As<IInvestmentService>();
builder.RegisterType<BrokerService>().As<IBrokerService>().As<IListService<Broker>>();
builder.RegisterType<PortfolioManagerService>().As<IListService<PortfolioManager>>();

builder.RegisterModelBinderProvider();

var container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
4

2 回答 2

4

.Build在调用该方法之前,您需要注册包含您的控制器的程序集:

builder.RegisterControllers(typeof(MvcApplication).Assembly);
var container = builder.Build();

在此示例中,我假设您的应用程序类被调用MvcApplication并获取了它的程序集。如果您的控制器是在不同的程序集中定义的,您应该指定此程序集。

documentation of AutoFac有一个你可以经历的例子。

于 2013-02-17T09:54:28.400 回答
0

在调用 builder.Build 方法之前尝试添加:

builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource(x => !(x.IsValueType) && !(x.IsAssignableFrom(typeof(string)))));
于 2016-05-05T15:47:21.140 回答