在尝试LightInject IoC容器http://www.lightinject.net/时,它会在解析ISomeService类型时抛出stackoverflow异常:
所有类型都在App_Start中注册:
container.RegisterAssembly("MyApp*.dll");
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试在控制器中解决它时,它会失败并抛出stackoverflow异常:
public SomeController(ISomeService someService)
{
_someService = someService;
}
Run Code Online (Sandbox Code Playgroud)
使用ServiceLocator时也会出现相同的错误:
ServiceLocator.Current.GetInstance<ISomeService>();
Run Code Online (Sandbox Code Playgroud)
我已经跟踪了它,我可以看到它在LightInject ServiceContainer类中失败了,但是我不明白它为什么会失败.
public object GetInstance(Type serviceType)
{
return GetDefaultDelegate(serviceType, true)(constants.Items);
}
Run Code Online (Sandbox Code Playgroud)
在调用GetDefaultDelegate之后,执行路径再次在GetInstance中结束,导致无限循环和堆栈溢出.
编辑2 - 进一步跟踪它,它似乎是由SomeService同时具有构造函数和属性注入引起的:
public class SomeService : ISomeService
{
public IAnotherService AnotherService { get; set; }
public SomeService(IAnotherService anotherService)
{
AnotherService = anotherService;
}
}
Run Code Online (Sandbox Code Playgroud)
依赖IAnotherService AnotherService是通过构造函数和属性注入的,但是无意使用属性注入器.
编辑3
应用程序中有几个层都使用ServiceLocator,所以我最初使用NuGet将LI添加到自己的项目中,所以我有:
MyApp.IoC.LightInject
MyApp.Repositories
MyApp.Services
MyApp.Web.UI
Run Code Online (Sandbox Code Playgroud)
但实际上并不需要将其添加到自己的项目中,因为可以在UI层中设置服务定位器提供程序:
var serviceLocator = new LightInjectServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);
Run Code Online (Sandbox Code Playgroud)
所以我刚刚删除了额外的项目,并将NuGet包放入UI层.我还安装了LightInject.Annotation并故意不调用container.EnableAnnotatedPropertyInjection()方法,以确保只使用构造函数注入.它仍在抛出stackoverflow.
要测试解析是否正常,我只是在HomeController.Index()方法中执行此操作:
public ActionResult Index()
{
var a = …Run Code Online (Sandbox Code Playgroud) c# ioc-container inversion-of-control service-locator light-inject