一开始我使用asp.net mvc和unity.mvc为DI启动项目,然后想将web api添加到同一项目并安装unity.webapi但是现在统一依赖注入无法将服务实例注入ApiControllers但是控制器类正在工作 .
UnityConfig.cs
public static class UnityConfig
{
private static Lazy<IUnityContainer> container =
new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
public static IUnityContainer Container => container.Value;
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IEmployeeService, EmployeeService>();
container.RegisterType<IRepository<Employee>, Repository<Employee>>();
}
}
ApiController.cs
public class EmployeeApiController : ApiController
{
private readonly IEmployeeService _employeeService;
public EmployeeApiController(IEmployeeService employeeService)
{
_employeeService = employeeService;
}
public EmployeeApiController(){}
// GET: api/EmployeeApi
public IEnumerable<Employee> Get()
{
var a = _employeeService.GetAll();
return a;
}
}
的Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
在apitroller的get动作中,IService通过空指针异常 .
2 回答
Web API定义了以下用于解决依赖关系的接口:
正如您在评论中指出的那样,Unity.WebApi nuget包提供了这种实现,您只需在应用程序启动时注册即可 .
完整参考:
找到解决方案:在UnityConfig.cs上添加以下行: