使用Autofac在WebAPI(包括OWIN)中无法解析依赖关系

时间:2016-12-22 10:00:26

标签: asp.net-web-api dependency-injection asp.net-mvc-5 asp.net-web-api2 autofac

我的global.asax如下所示

private void BuildIocContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterModule(new BootstrapModule());
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); //Set the WebApi DependencyResolver
    }

    protected void Application_Start()
    {
        BuildIocContainer();
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

我为autofac构建了一个bootstrap模块,如下面的那个

public class BootstrapModule : Autofac.Module
{
    private Assembly AssemblyOf<T>()
    {
        return typeof(T).Assembly;
    }

    private Assembly WebAssembly
    {
        get { return Assembly.GetExecutingAssembly(); }
    }

    private void RegisterMvc(ContainerBuilder builder)
    {
        builder.RegisterType<AsyncControllerActionInvoker>()
            .As<IActionInvoker>();

        builder.RegisterControllers(WebAssembly)
            .InjectActionInvoker();
        builder.RegisterApiControllers(WebAssembly).InjectActionInvoker();
    }

    private void RegisterLogger(ContainerBuilder builder)
    {
        builder.Register(CreateLogger)
            .SingleInstance();
        builder.Register(_ => new NLogWrapper(LogManager.GetLogger("DefaultLogger")))
            .As<Logging.ILogger>()
            .SingleInstance();
    }

    private static System.Func<Type, Logging.ILogger> CreateLogger(IComponentContext componentContext)
    {
        return type => new NLogWrapper(LogManager.GetLogger(type.FullName));
    }

    protected override void Load(ContainerBuilder builder)
    {
        RegisterLogger(builder);
        RegisterMvc(builder);
        builder.RegisterAssemblyTypes(WebAssembly)
                .AsImplementedInterfaces();

        builder.RegisterType<UserService>()
        .As<IUserService>()
        .InstancePerRequest();            
        builder.RegisterAssemblyTypes(typeof(IUserService).Assembly)
               .AsImplementedInterfaces();
        builder.RegisterAssemblyTypes(typeof(IUserRepository).Assembly)
                .AsImplementedInterfaces();
        builder.RegisterFilterProvider();
    }
}

现在,当我尝试通过邮递员客户端点击帐户控制器时,

private IUserService _userService;

    public AccountController(IUserService userService)
    {
        _userService = userService;
    }



    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public HttpStatusCode Register(User model)
    {
        if (!ModelState.IsValid)
        {
            return HttpStatusCode.BadRequest;
        }

        // TODO : Write mapper if needed
        var user = new ToolUser()
        {
            FirstName = model.FirstName,
            LastName = model.LastName,
            EmailID = model.EmailID,
            DOB = Convert.ToDateTime(model.DateOfBirth),
            Gender = model.Gender.ToString(),
            TenandID = model.TenantID,
            Password = model.Password
        };

        HttpStatusCode result = _userService.RegisterUser(user);

        return result;
    }

我收到错误

  

“尝试创建'AccountController'类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。”

我做错了什么?

1 个答案:

答案 0 :(得分:3)

你应该有类似的东西 HttpConfiguration config = new HttpConfiguration(); 某处,你用它来注册你的路线等。

将该配置传递给BuildIocContainer() mehod并添加行

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

而不是

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); //Set the WebApi DependencyResolver

希望有所帮助