0

我收到“ AutoFac Practice.dll 中发生‘System.NullReferenceException’类型的异常,但未在用户代码中处理”我的 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";
    }
}

在控制器中,我在这一行收到错误:return _repository.Print(); 说对象引用未设置。_repository 没有被引用我不知道我在配置中缺少什么。

4

1 回答 1

1

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

所以代替这个:

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

你必须这样做:

public HomeController(IDBRepository repository)
{
    _repository = repository;
}
于 2016-08-31T07:51:28.333 回答