1

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;
    }

1 Answers1

0

As you are using ambient scope context you can consume / inject DbContext as Func<DbContext> in your singletons. Then whenever Func is called, it will return value bound to current ambient scope / request.

dadhi
  • 4,807
  • 19
  • 25
  • Do you have an example how to make a generic registration method like this sample? ` public static IContainer RegisterWebRequest(this IContainer container,) { container.Register, Func>(reuse: Reuse.InWebRequest, made: Made.Of(() => new T()), ifAlreadyRegistered: IfAlreadyRegistered.Replace); return container; ` – Lucas Massena Oct 24 '16 at 15:09
  • Please, ignore my last comment. I have created a issue on your bitbucket: https://bitbucket.org/dadhi/dryioc/issues/378/resolve-a-single-instance-inwebrequest – Lucas Massena Oct 24 '16 at 20:24