我收到“ 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 没有被引用我不知道我在配置中缺少什么。