I am trying to create completely Singleton applications (Web and Console). But the Entity DbContext should be used PerWebRequest on web.
How should I register it on container to support this? I understand once the class has been initialized as a singleton, I will be running on a single instance on Memory with all injected classes as a Singleton too.
The following code is my Container Initialization for all web applications and console applications. - How should I register when it is running in Console? - When running on Web and Owin calls startup things, sometimes I need to resolve objects to use on Authentication, but Owin runs on "no context" environment. How to detect and use it?
private static IContainer Initialize(IContainer container)
{
if (container == null)
container = new Container(
rules => rules
.WithDefaultReuseInsteadOfTransient(Reuse.InWebRequest)
.WithFactorySelector(Rules.SelectLastRegisteredFactory())
.With(FactoryMethod.ConstructorWithResolvableArguments)
.WithoutThrowOnRegisteringDisposableTransient(),
scopeContext: new AsyncExecutionFlowScopeContext()
);
string prefix = GetPrefix();
var implementingClasses =
AppDomain.CurrentDomain.GetAssemblies().ToList()
.Where(x => x.FullName.StartsWith(prefix))
.SelectMany(x => x.GetTypes())
.Where(type =>
(type.Namespace != null && type.Namespace.StartsWith(prefix)) &&
type.IsPublic && // get public types
!type.IsAbstract && // which are not interfaces nor abstract
type.GetInterfaces().Length != 0); // which implementing some interface(s)
Parallel.ForEach(implementingClasses, implementingClass =>
{
container.RegisterMany(new[] { implementingClass }, Reuse.Singleton, serviceTypeCondition: type => type.IsInterface);
});
return container;
}
答案 0 :(得分:0)
当您使用环境范围上下文时,您可以在单身中使用/注入DbContext为Func<DbContext>
。然后,每当调用Func时,它将返回绑定到当前环境范围/请求的值。