Exemplo n.º 1
0
        public void DryIoc_own_Register_ReuseScope_dependency_in_a_Singleton_IS_Validated_as_captive_dependency()
        {
            var services = new ServiceCollection();

            services.AddScoped <Foo>();      // Actually a `ScopedOrSingleton` due MS.DI convention
            services.AddSingleton <Bar>();

            // These two line are "presumably" done by the framework
            var providerFactory = new DryIocServiceProviderFactory();
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            // Getting back the underlying DryIoc container to use its functions (it is always implicitly available).
            var container = provider.GetRequiredService <IContainer>();

            // IMPORTANT line
            container.Register <Buz>(Reuse.Scoped);

            var errors = container.Validate(ServiceInfo.Of <Foo>());

            Assert.AreEqual(1, errors.Length);
            var error = errors[0].Value;

            Assert.AreEqual(Error.NameOf(Error.DependencyHasShorterReuseLifespan), error.ErrorName);

            /* Exception message:
             *
             * code: Error.DependencyHasShorterReuseLifespan;
             * message: Dependency Buz as parameter "buz" (IsSingletonOrDependencyOfSingleton) with reuse Scoped {Lifespan=100} has a shorter lifespan than its parent's Singleton Bar as parameter "bar" FactoryId=145 (IsSingletonOrDependencyOfSingleton)
             * in resolution root Scoped Foo FactoryId=144
             * from container without scope
             * with Rules with {UsedForValidation} and without {ImplicitCheckForReuseMatchingScope, EagerCachingSingletonForFasterAccess} with TotalDependencyCountInLambdaToSplitBigObjectGraph=2147483647
             * If you know what you're doing you may disable this error with the rule `new Container(rules => rules.WithoutThrowIfDependencyHasShorterReuseLifespan())`.
             */
        }
Exemplo n.º 2
0
        public void GetRequiredService_throws_InvalidOperationException_now()
        {
            var services        = new ServiceCollection();
            var providerFactory = new DryIocServiceProviderFactory();
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            Assert.Throws <InvalidOperationException>(() =>
                                                      provider.GetRequiredService <Buz>());
        }
Exemplo n.º 3
0
        public void GetService_should_throw_with_the_global_rule_set()
        {
            var services        = new ServiceCollection();
            var container       = new Container(rules => rules.WithServiceProviderGetServiceShouldThrowIfUnresolved());
            var providerFactory = new DryIocServiceProviderFactory(container);
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            Assert.Throws <ContainerException>(() =>
                                               provider.GetService <Buz>());
        }
        public void Test1()
        {
            var services = new ServiceCollection();

            services.AddTransient <MyService>();
            services.AddOptions <AgentOptions>();

            var providerFactory = new DryIocServiceProviderFactory();
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            provider.GetRequiredService <IResolver>();

            var service = provider.GetRequiredService <MyService>();

            Assert.IsNotNull(service.AgentOptions);
        }
Exemplo n.º 5
0
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(new WebApplicationOptions
            {
                Args            = args,
                ContentRootPath = Directory.GetCurrentDirectory(),
                // etc.
            });


            // ## Dependency Injection stuff
            // -----------------------------------------------------------
            var container = new Container(rules =>
                                          // optional: Enables property injection for Controllers
                                          rules.With(propertiesAndFields: request => request.ServiceType.Name.EndsWith("Controller")
                    ? PropertiesAndFields.Properties()(request)
                    : null));

            container.RegisterMyBusinessLogic();

            // Here it goes the integration with the existing DryIoc container
            var diFactory = new DryIocServiceProviderFactory(container, ExampleOfCustomRegisterDescriptor);

            builder.Host.UseServiceProviderFactory(diFactory);

            builder.Services
            .AddMvc(options => options.EnableEndpointRouting = false)
            .AddControllersAsServices();

            // other things...
            builder.Logging.ClearProviders();
            builder.Logging.AddConsole();
            //-----------------------------------------------------------


            var app = builder.Build();

            app.UseMvc();
            app.UseHttpsRedirection();
            app.UseAuthorization();

            app.Run();
        }
Exemplo n.º 6
0
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var iocProviderFatory = new DryIocServiceProviderFactory();

            Startup.JobActivator = new NeonTetraJobActivator();
            var hostBuilder = Host.CreateDefaultBuilder(args)
                              .UseServiceProviderFactory(iocProviderFatory)
                              .ConfigureWebHostDefaults(webBuilder =>
            {
                var webHostBuilder = webBuilder.UseStartup <Startup>();
            })
                              .ConfigureContainer <Container>((hostContext, container) =>
            {
                Startup.Deployment = InitializeApplication(container).Result;
                (Startup.JobActivator as NeonTetraJobActivator).Resolver = Startup.Deployment.Container;
            })
            ;

            return(hostBuilder);
        }
Exemplo n.º 7
0
        public void ServiceCollection_AddScoped_dependency_in_a_Singleton_is_Not_validated_as_captive_dependency()
        {
            var services = new ServiceCollection();

            services.AddScoped <Foo>();      // Actually a `ScopedOrSingleton` due MS.DI convention
            services.AddSingleton <Bar>();
            services.AddScoped <Buz>();      // Actually a `ScopedOrSingleton` due MS.DI convention

            // These two line are "presumably" done by the framework
            var providerFactory = new DryIocServiceProviderFactory();
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            // Getting back the underlying DryIoc container to use its functions (it is always implicitly available).
            var container = provider.GetRequiredService <IContainer>();

            var errors = container.Validate(ServiceInfo.Of <Foo>());

            // No errors (!) is because due MS.DI conventions `AddScoped` adds a service as a `ScopedOrSingleton`,
            // which is perfectly fine to have inside the a `Singleton`
            Assert.AreEqual(0, errors.Length);
        }
Exemplo n.º 8
0
        public async Task GetRequiredServiceAsync()
        {
            var services = new ServiceCollection();

            services.AddSingleton <IRemoteConnectionFactory, TestConnectionFactory>();
            services.AddSingleton <IRemoteConnection>(sp =>
            {
                var factory = sp.GetRequiredService <IRemoteConnectionFactory>();
                return(factory.ConnectAsync());
            });

            var providerFactory = new DryIocServiceProviderFactory();
            var provider        = providerFactory.CreateServiceProvider(providerFactory.CreateBuilder(services));

            var connection1 = await provider.GetRequiredServiceAsync <IRemoteConnection>();

            Assert.IsNotNull(connection1);

            var connection2 = await provider.GetRequiredServiceAsync <IRemoteConnection>();

            Assert.AreSame(connection2, connection1);

            await connection2.PublishAsync("hello", "sailor");
        }