我必须区分使用相同接口的类。通过使用这些类在LightInject.Interceptor上,我想抛出异常。如果我在Asp.Net Core上的单个类上实现Dependecies,我没有任何问题(我在'ExceptionInterceptor'类中捕获了'breakpoint'),但是当我同时使用这两个类时,我确实遇到了问题(我不能捕获了“ ExceptionInterceptor”类的“ breakpoint”)。我该如何解决?
Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddControllersAsServices();
services.AddSingleton<Servis1>();
services.AddSingleton<Servis2>();
services.AddSingleton<Func<string, IServis>>(serviceProvider => key =>
{
switch (key)
{
case "Servis1":
return serviceProvider.GetService<Servis1>();
case "Servis2":
return serviceProvider.GetService<Servis2>();
default:
throw new KeyNotFoundException();
}
});
//LightInject container
var containerOptions = new ContainerOptions { EnablePropertyInjection = false, };
var container = new ServiceContainer(containerOptions);
container.Intercept(sr => sr.ServiceType == typeof(IServis), (sf, pd) => pd.Implement(() => new ExceptionInterceptor()));
return container.CreateServiceProvider(services);
}
我的Servis界面
public interface IServis
{
void Fonksiyon();
}
我的服务类实现了Servis接口(servis2与servis1相同)
public class Servis1 : IServis
{
public void Fonksiyon()
{
throw new Exception("have a problem S1");
}
}
这是我的控制人
private readonly Func<string, IServis> _serviceAccessor;
public ValuesController(Func<string, IServis> serviceAccessor)
{
_serviceAccessor = serviceAccessor;
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
_serviceAccessor("Servis1").Fonksiyon();
_serviceAccessor("Servis2").Fonksiyon();
return new string[] { "value1", "value2" };
}
这是ExceptionInterceptor
public class ExceptionInterceptor : IInterceptor
{
public ExceptionInterceptor()
{
}
public object Invoke(IInvocationInfo invocation)
{
try
{
return invocation.Proceed();
}
catch (Exception e)
{
throw new Exception();
}
}
}