我有这个简单的界面和具体类型:
public interface IIdentifierGenerator {
long Generate(Type type);
long Generate<TType>(TType type);
}
public HiloIdentifierGenerator : IIdentifierGenerator { /* implementation... */ }
我创建了这个DependencyResolver
:
public class SelfHostedSimpleInjectorWebApiDependencyResolver : IDependencyResolver {
private readonly Container _container;
private readonly LifetimeScope _lifetimeScope;
public SelfHostedSimpleInjectorWebApiDependencyResolver(
Container container)
: this(container, false) {
}
private SelfHostedSimpleInjectorWebApiDependencyResolver(
Container container, bool createScope) {
_container = container;
if (createScope)
_lifetimeScope = container.BeginLifetimeScope();
}
public IDependencyScope BeginScope() {
return new SelfHostedSimpleInjectorWebApiDependencyResolver(
_container, true);
}
public object GetService(Type serviceType) {
return ((IServiceProvider)_container).GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType) {
return _container.GetAllInstances(serviceType);
}
public void Dispose() {
if (_lifetimeScope != null)
_lifetimeScope.Dispose();
}
}
我这样配置我的服务器:
_config = new HttpSelfHostConfiguration("http://192.168.1.100:20000");
_config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
_config.DependencyResolver =
new SelfHostedSimpleInjectorWebApiDependencyResolver(
IoC.Wrapper.GetService<Container>());
_server = new HttpSelfHostServer(_config);
/* etc. */
这是我的控制器:
public class IdentifierController : ApiController {
private readonly IIdentifierGenerator _identifierGenerator;
public IdentifierController(IIdentifierGenerator identifierGenerator) {
_identifierGenerator = identifierGenerator;
}
public long Get(string id) {
var type = Type.GetType(id, false, true);
return type == null ? -1 : _identifierGenerator.GetIdentifier(type);
}
}
现在,当我调用 action 方法时,我得到了这个错误:
跨线程使用 LifetimeScope 实例是不安全的。确保生命周期范围内的完整操作在同一个线程中执行,并确保 LifetimeScope 实例在创建时被释放在同一个线程上。Dispose 在 ManagedThreadId 28 的线程上调用,但在 id 为 29 的线程上创建。
我在哪里做错了?你能帮忙吗?