与ApiController一起使用时出现AutoFac NullReferenceException

时间:2016-05-20 19:58:14

标签: c# dependency-injection controller autofac nullreferenceexception

我试图在我的ApiControllers中连接依赖注入。我不认为AutoFac正在实例化界面,因为我一直收到以下错误:

  

对象引用未设置为对象的实例。

public class UserformsController : ApiController
{
    private IUserformsRepository _userformRepo;

    public UserformsController(){}

    public UserformsController(IUserformsRepository userformRepo)
    {
        this._userformRepo = userformRepo;
    }

    [HttpGet]
    public object Get(string userId, int formId)
    {
        return _userformRepo.GetUserform(userId, formId);
    }
}

这是配置。我确定我错过了一些东西,但我无法弄清楚是什么。

public static void RegisterDependencies()
    {
        #region Create the builder

        var builder = new ContainerBuilder();

        #endregion Create the builder

        #region Setup a common pattern

        // placed here before RegisterControllers as last one wins
        builder.RegisterAssemblyTypes()
               .Where(t => t.Name.EndsWith("Repository"))
               .AsImplementedInterfaces()
               .InstancePerRequest();
        builder.RegisterAssemblyTypes()
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces()
               .InstancePerRequest();

        #endregion Setup a common pattern

        #region Register modules

        builder.RegisterAssemblyModules(typeof(ApiController).Assembly);

        #endregion Register modules

        #region Register Controllers in Assembly

        builder.RegisterControllers(typeof(ApiController).Assembly);

        #endregion Register Controllers in Assembly

        #region Inject HTTP Abstractions

        /*
         The MVC Integration includes an Autofac module that will add HTTP request
         lifetime scoped registrations for the HTTP abstraction classes. The
         following abstract classes are included:
        -- HttpContextBase
        -- HttpRequestBase
        -- HttpResponseBase
        -- HttpServerUtilityBase
        -- HttpSessionStateBase
        -- HttpApplicationStateBase
        -- HttpBrowserCapabilitiesBase
        -- HttpCachePolicyBase
        -- VirtualPathProvider

        To use these abstractions add the AutofacWebTypesModule to the container
        using the standard RegisterModule method.
        */
        builder.RegisterModule<AutofacWebTypesModule>();

        #endregion Inject HTTP Abstractions

        #region Register Global Filters

        builder.RegisterFilterProvider();

        #endregion Register Global Filters

        #region Set the MVC dependency resolver to use Autofac

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        #endregion Set the MVC dependency resolver to use Autofac
    }

0 个答案:

没有答案