public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should add another implemenetation.
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                var mockType = typeof(Mock<>).MakeGenericType(serviceType.Key);
                services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType));
            }

            // Act
            services.AddMvc();

            // Assert
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1);

                foreach (var implementationType in serviceType.Value)
                {
                    AssertContainsSingle(services, serviceType.Key, implementationType);
                }
            }
        }
示例#2
0
            protected override void Load(ContainerBuilder builder)
            {
                var services2 = new ServiceCollection();
                services2.AddMvc();
                services2.ConfigureRazorViewEngine(options =>
                {
                    options.ViewLocationExpanders.Add(new TestViewLocationExpander());
                });

                builder.Populate(services2);
            }
        public ShoppingCartControllerTest()
        {
            var services = new ServiceCollection();

            services.AddEntityFramework()
                      .AddInMemoryStore()
                      .AddDbContext<MusicStoreContext>();

            services.AddMvc();

            _serviceProvider = services.BuildServiceProvider();
        }
示例#4
0
            protected override void Load(ContainerBuilder builder)
            {
                Console.WriteLine("Registering Module");

                var services2 = new ServiceCollection();
                services2.AddMvc();
                services2.ConfigureRazorViewEngine(options => {
                    Console.WriteLine("Registering TestViewLocationExpander");
                    options.ViewLocationExpanders.Add(new TestViewLocationExpander());
                });

                builder.Populate(services2);
            }
        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) {
            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped<IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            serviceCollection.AddMvc();

            serviceCollection.Configure<RazorViewEngineOptions>(options => {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);
            });

            var p = _serviceProvider.GetService<IOrchardLibraryManager>();
            serviceCollection.AddInstance<IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService<IAssemblyLoaderContainer>()));

            foreach (var dependency in blueprint.Dependencies) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    Logger.Debug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof (ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            //foreach (var item in blueprint.Controllers) {
            //    var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
            //    var serviceKeyType = item.Type;
            //    serviceCollection.AddScoped(serviceKeyType);

            //}

            return BuildFallbackServiceProvider(
                            serviceCollection,
                            _serviceProvider);
        }
        public static void UseScriptConsole(this IApplicationBuilder app, IServiceCollection theServices)
        {
            var appS = app.ApplicationServices;
            var scriptManager = new ScriptManager();

            var services = new ServiceCollection();
            services.Clear();
            foreach (var s in theServices)
               services.Insert(0, s);

            services.AddInstance<ScriptManager>(scriptManager);
            var fp = new DebugFileProvider(new EmbeddedFileProvider(typeof(ScriptConsoleBuilderExtensions).Assembly, "ScriptConsole"));

            services
                .AddMvc()
                .AddControllersAsServices(new[] { typeof(ScriptConsoleController), typeof(HomeController) })
                .AddRazorOptions(r => r.FileProvider = fp);

            services.AddLogging();
            var provider = services.BuildServiceProvider();

            app.Map("/ScriptConsole", builder =>
            {
                var routeBuilder = new RouteBuilder()
                {
                    DefaultHandler = new MvcRouteHandler(),
                    ServiceProvider = new ShadowedServiceProvider(provider, app.ApplicationServices)
                };
                routeBuilder.MapRoute("ScriptConsole", "{action}", new { controller = "ScriptConsole", action = "Index" });
                routeBuilder.MapRoute("ScriptConsoleX", "{controller}/{action}", new { controller = "ScriptConsole", action = "Index" });

                var route = routeBuilder.Build();
                builder.Use(next =>
                {
                    return async (context) =>
                    {
                        context.ApplicationServices = new ShadowedServiceProvider(provider, context.ApplicationServices);
                        context.RequestServices = new ShadowedServiceProvider(provider, context.RequestServices);
                        await route.RouteAsync(new RouteContext(context));
                    };
                });

            });
        }
        public void SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should not replace it.
            foreach (var serviceType in SingleRegistrationServiceTypes)
            {
                var mockType = typeof(Mock<>).MakeGenericType(serviceType);
                services.Add(ServiceDescriptor.Transient(serviceType, mockType));
            }

            // Act
            services.AddMvc();

            // Assert
            foreach (var singleRegistrationType in SingleRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, singleRegistrationType, 1);
            }
        }
示例#8
0
        private static void InitializeServices(HttpContext httpContext, Action<MvcOptions> updateOptions = null)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddMvc();

            httpContext.RequestServices = serviceCollection.BuildServiceProvider();

            var actionContext = new ActionContext(httpContext, new RouteData(), new ControllerActionDescriptor());

            var actionContextAccessor =
                httpContext.RequestServices.GetRequiredService<IScopedInstance<ActionContext>>();
            actionContextAccessor.Value = actionContext;

            var options = new TestMvcOptions().Options;
            if (updateOptions != null)
            {
                updateOptions(options);
            }

            var actionBindingContextAccessor =
                httpContext.RequestServices.GetRequiredService<IScopedInstance<ActionBindingContext>>();
            actionBindingContextAccessor.Value = GetActionBindingContext(options, actionContext);
        }
示例#9
0
文件: Startup.cs 项目: Nakro/Mvc
        public void Configure(IBuilder app)
        {
            app.UseFileServer();
#if NET45
            var configuration = new Configuration()
                                    .AddJsonFile(@"App_Data\config.json")
                                    .AddEnvironmentVariables();

            string diSystem;

            if (configuration.TryGet("DependencyInjection", out diSystem) && 
                diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase))
            {
                app.UseMiddleware<MonitoringMiddlware>();

                var services = new ServiceCollection();

                services.AddMvc();
                services.AddSingleton<PassThroughAttribute>();
                services.AddSingleton<UserNameService>();
                services.AddTransient<ITestService, TestService>();                
                services.Add(OptionsServices.GetDefaultServices());

                // Create the autofac container 
                ContainerBuilder builder = new ContainerBuilder();

                // Create the container and use the default application services as a fallback 
                AutofacRegistration.Populate(
                    builder,
                    services,
                    fallbackServiceProvider: app.ApplicationServices);

                builder.RegisterModule<MonitoringModule>();

                IContainer container = builder.Build();

                app.UseServices(container.Resolve<IServiceProvider>());
            }
            else
#endif
            {
                app.UseServices(services =>
                {
                    services.AddMvc();
                    services.AddSingleton<PassThroughAttribute>();
                    services.AddSingleton<UserNameService>();
                    services.AddTransient<ITestService, TestService>();
                });
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action}");

                routes.MapRoute(
                    "controllerActionRoute",
                    "{controller}/{action}",
                    new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    "controllerRoute",
                    "{controller}",
                    new { controller = "Home" });
            });
        }
        public void AddMvcServicesTwice_DoesNotAddDuplicates()
        {
            // Arrange
            var services = new ServiceCollection();

            // Act
            services.AddMvc();
            services.AddMvc();

            // Assert
            var singleRegistrationServiceTypes = SingleRegistrationServiceTypes;
            foreach (var service in services)
            {
                if (singleRegistrationServiceTypes.Contains(service.ServiceType))
                {
                    // 'single-registration' services should only have one implementation registered.
                    AssertServiceCountEquals(services, service.ServiceType, 1);
                }
                else if (service.ImplementationType != null && !service.ImplementationType.Assembly.FullName.Contains("Mvc"))
                {
                    // Ignore types that don't come from MVC
                }
                else
                {
                    // 'multi-registration' services should only have one *instance* of each implementation registered.
                    AssertContainsSingle(services, service.ServiceType, service.ImplementationType);
                }
            }
        }