Autofac Null引用错误web api 2

时间:2016-08-31 07:34:53

标签: asp.net-web-api2 autofac autofac-configuration

我得到" 类型' System.NullReferenceException'发生在AutoFac Practice.dll中但未在用户代码中处理" 我的Autofac代码和配置是:

Autofac配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var builder = new ContainerBuilder();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // OPTIONAL: Register the Autofac filter provider.
        builder.RegisterWebApiFilterProvider(config);

        builder.RegisterType<SqlServerRepository>().As<IDBRepository>().InstancePerRequest();

        // Set the dependency resolver to be Autofac.
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

控制器代码:

 public class HomeController : ApiController
{
    IDBRepository _repository;

    void Home(IDBRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public string Print()
    {
        return _repository.Print();
    }
}

存储库

interface IDBRepository
{
    //void Select();
    //void Insert();
    //void Update();
    //void Delete();

    string Print();
}

public class SqlServerRepository : IDBRepository
{
    public string Print()
    {
        return "hello there, i am Sql Server";
    }
}

在Controller中我遇到错误: return _repository.Print(); 表示未设置对象引用。 _repository没有被引用我不知道我缺少配置。

1 个答案:

答案 0 :(得分:1)

您必须在控制器的构造函数中设置依赖项(IDBRepository)。

所以不要这样:

void Home(IDBRepository repository)
{
    _repository = repository;
}

你必须这样做:

public HomeController(IDBRepository repository)
{
    _repository = repository;
}