我正在构建一个ASP.net WebApi,并试图同时使用Entity。我正在遵循本指南。
Getting Started with ASP.NET Web API 2 (C#)
我使用Fiddler收到500内部服务器错误。 JSON异常消息指出ExceptionMessage=An error occurred when trying to create a controller of type 'LocationsController'. Make sure that the controller has a parameterless public constructor.
这是Controller.cs
[RoutePrefix("api/Locations")]
public class LocationsController : ApiController
{
// GET api/<controller>
private IlocationsRepository LocationsRepo;
public LocationsController(IlocationsRepository _repo)
{
if (_repo == null) { throw new ArgumentNullException("_repo"); }
LocationsRepo = _repo;
}
[HttpGet]
[Route("")]
public IEnumerable<Location> GetAll()
{
return LocationsRepo.GetAll();
}
}
我无法使用无参数的公共构造函数,因为我需要使用为Locations
创建的数据库存储库。我通过执行以下操作验证了问题是IlocationsRepository
。
当我用没有参数替换LocationsController
构造函数时,在控制器中声明List<Location>
并使用虚拟数据。我收到200
,其中所有json数据都正确无误。
以下是Global.asax.cs文件的开头
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Session_Start(object sender, EventArgs e)
{
}
}
好像我需要在Global中进行依赖注入,但没有一个指南有关于这部分的任何信息。
对于后代,这里是ContextDB cs
public class WebServerContext : DbContext
{
public WebServerContext() : base("WebServerContext") {}
public DbSet<Order> dOrders { get; set; }
public DbSet<Location> dLocations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
对于其他后代,这里是Locations Repository。
public class LocationsRepository : IlocationsRepository
{
private z_Data.WebServerContext db = new z_Data.WebServerContext();
public void Add(Location item)
{
db.dLocations.Add(item);
}
public IEnumerable<Location> GetAll()
{
return db.dLocations;
}
}
答案 0 :(得分:4)
根据Dependency Injection for Web Api tutorial on MSDN,您缺少使用Web Api注册依赖项解析程序(实现System.Web.Http.IDependencyResolver
的具体类)的行。它就像你的DI容器和Web Api之间的桥梁,因此它可以解决你的构造函数依赖。
public static void Register(HttpConfiguration config)
{
var container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container); // <- You need this
// Other Web API configuration not shown.
}
当然,假设您使用的是Unity。如果没有,您应该使用DI容器附带的DependencyResolver或实现自己的。
注意:对于某些DI容器,您还需要明确注册所有控制器。