当前位置: 首页>>代码示例>>C#>>正文


C# ServiceCollection.AddInstance方法代码示例

本文整理汇总了C#中Microsoft.Framework.DependencyInjection.ServiceCollection.AddInstance方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddInstance方法的具体用法?C# ServiceCollection.AddInstance怎么用?C# ServiceCollection.AddInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Framework.DependencyInjection.ServiceCollection的用法示例。


在下文中一共展示了ServiceCollection.AddInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnValidatePrincipalTestSuccess

        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), 
                new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, 
                IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
开发者ID:stormwild,项目名称:Identity,代码行数:35,代码来源:SecurityStampValidatorTest.cs

示例2: CreateHttpContextAccessor

        public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
        {
            var services = new ServiceCollection();

            var request = new DefaultHttpContext().Request;
            request.Method = "GET";
            request.Path = new PathString("/Test");
            var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };

            services.AddInstance<IHttpContextAccessor>(contextAccessor);

            if (actionContext != null)
            {
                var si = new ActionContextAccessor();
                si.ActionContext = actionContext;
                services.AddInstance<IActionContextAccessor>(si);
            }

            if (requestTelemetry != null)
            {
                services.AddInstance<RequestTelemetry>(requestTelemetry);
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            contextAccessor.HttpContext.RequestServices = serviceProvider;

            return contextAccessor;
        }
开发者ID:hackathonvixion,项目名称:ApplicationInsights-aspnet5,代码行数:28,代码来源:HttpContextAccessorHelper.cs

示例3: ConfigureServices

        public void ConfigureServices()
        {
            IServiceProvider mainProv = CallContextServiceLocator.Locator.ServiceProvider;
            IApplicationEnvironment appEnv = mainProv.GetService<IApplicationEnvironment>();
            IRuntimeEnvironment runtimeEnv = mainProv.GetService<IRuntimeEnvironment>();

            ILoggerFactory logFactory = new LoggerFactory();
            logFactory.AddConsole(LogLevel.Information);

            ServiceCollection sc = new ServiceCollection();
            sc.AddInstance(logFactory);
            sc.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
            sc.AddEntityFramework()
                .AddSqlite()
                .AddDbContext<StarDbContext>();

            sc.AddSingleton<ILibraryManager, LibraryManager>(factory => mainProv.GetService<ILibraryManager>() as LibraryManager);
            sc.AddSingleton<ICache, Cache>(factory => new Cache(new CacheContextAccessor()));
            sc.AddSingleton<IExtensionAssemblyLoader, ExtensionAssemblyLoader>();
            sc.AddSingleton<IStarLibraryManager, StarLibraryManager>();
            sc.AddSingleton<PluginLoader>();
            sc.AddSingleton(factory => mainProv.GetService<IAssemblyLoadContextAccessor>());
            sc.AddInstance(appEnv);
            sc.AddInstance(runtimeEnv);

            Services = sc;

            ServiceProvider = sc.BuildServiceProvider();
        }
开发者ID:SharpStar,项目名称:Star2,代码行数:29,代码来源:Startup.cs

示例4: GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate

        public void GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate()
        {
            // Arrange
            List<string> output = new List<string>();

            var mockKeyEscrowSink1 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink1.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink1] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var mockKeyEscrowSink2 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink2.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink2] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink2.Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act
            var sink = services.GetKeyEscrowSink();
            sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("<theElement />"));

            // Assert
            Assert.Equal(new[] { "[sink1] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement", "[sink2] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output);
        }
开发者ID:hishamco,项目名称:DataProtection,代码行数:31,代码来源:KeyEscrowServiceProviderExtensionsTests.cs

示例5: GetServiceCollectionWithContextAccessor

 public static ServiceCollection GetServiceCollectionWithContextAccessor()
 {
     var services = new ServiceCollection();
     IHttpContextAccessor contextAccessor = new HttpContextAccessor();
     services.AddInstance<IHttpContextAccessor>(contextAccessor);
     services.AddInstance<INotifier>(new Notifier(new ProxyNotifierMethodAdapter()));
     return services;
 }
开发者ID:hackathonvixion,项目名称:ApplicationInsights-aspnet5,代码行数:8,代码来源:ApplicationInsightsExtensionsTests.cs

示例6: CreateContainer

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

            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof (IModule).IsAssignableFrom(t.Type))) {

                Logger.Debug("IModule Type: {0}", dependency.Type);

                // TODO: Rewrite to get rid of reflection.
                var instance = (IModule) Activator.CreateInstance(dependency.Type);
                instance.Configure(serviceCollection);
            }

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

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type)))
            {
                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);
                    }
                }
            }

            serviceCollection.AddLogging();

            return new WrappingServiceProvider(_serviceProvider, serviceCollection);
        }
开发者ID:fengyeju,项目名称:Brochard,代码行数:54,代码来源:ShellContainerFactory.cs

示例7: RegisterServices

 public static IServiceProvider RegisterServices(IEnumerable<IViewLocator> viewLocators, IEnumerable<IStaticFileLocator> staticFileLocators)
 {
     // register types for IServiceProvider here
     var serviceCollection = new ServiceCollection();
     serviceCollection.AddInstance(typeof(IEnumerable<IViewLocator>), viewLocators);
     serviceCollection.AddInstance(typeof(IEnumerable<IStaticFileLocator>), staticFileLocators);
     serviceCollection.AddTransient<IViewLocatorService, ViewLocatorService>();
     serviceCollection.AddTransient<IStaticFileGeneratorService, StaticFileGeneratorService>();
     serviceCollection.AddTransient<IControllerRewriterService, ControllerRewriterService>();
     serviceCollection.AddTransient<IControllerGeneratorService, ControllerGeneratorService>();
     serviceCollection.AddTransient<R4MvcGenerator, R4MvcGenerator>();
     return serviceCollection.BuildServiceProvider();
 }
开发者ID:kazuk,项目名称:R4MVC,代码行数:13,代码来源:IocConfig.cs

示例8: ConfigureServices

        public IServiceCollection ConfigureServices()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance<IAmazonS3>(new AmazonS3Client());
            serviceCollection.AddInstance<IAmazonCodeDeploy>(new AmazonCodeDeployClient());
            serviceCollection.AddInstance<IAmazonECS>(new AmazonECSClient());

            serviceCollection.AddInstance<IApplicationEnvironment>(this._appEnv);
            serviceCollection.AddInstance<IConfiguration>(this.Configuration);
            serviceCollection.AddSingleton<UtilityService>();

            return serviceCollection;
        }
开发者ID:jamisliao,项目名称:aws-sdk-net-samples,代码行数:14,代码来源:Program.cs

示例9: CreateContainer

        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);
        }
开发者ID:night-king,项目名称:OrchardNoCMS,代码行数:50,代码来源:ShellContainerFactory.cs

示例10: GetBindingContext

        private static ModelBindingContext GetBindingContext(Type modelType)
        {
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
            var modelMetadata = metadataProvider.GetMetadataForType(modelType);


            var services = new ServiceCollection();
            services.AddInstance<IService>(new Service());

            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = modelMetadata,
                ModelName = "modelName",
                FieldName = "modelName",
                ModelState = new ModelStateDictionary(),
                OperationBindingContext = new OperationBindingContext
                {
                    ModelBinder = new HeaderModelBinder(),
                    MetadataProvider = metadataProvider,
                    HttpContext = new DefaultHttpContext()
                    {
                        RequestServices = services.BuildServiceProvider(),
                    },
                },
                BinderModelName = modelMetadata.BinderModelName,
                BindingSource = modelMetadata.BindingSource,
                ValidationState = new ValidationStateDictionary(),
            };

            return bindingContext;
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:32,代码来源:ServiceModelBinderTest.cs

示例11: GetServiceCollectionWithContextAccessor

 public static ServiceCollection GetServiceCollectionWithContextAccessor()
 {
     var services = new ServiceCollection();
     IHttpContextAccessor contextAccessor = new HttpContextAccessor();
     services.AddInstance<IHttpContextAccessor>(contextAccessor);
     return services;
 }
开发者ID:modulexcite,项目名称:ApplicationInsights-aspnet5,代码行数:7,代码来源:ApplicationInsightsExtensionsTests.cs

示例12: CreateRoleManager

 public static RoleManager<IdentityRole> CreateRoleManager(InMemoryContext context)
 {
     var services = new ServiceCollection();
     services.AddIdentity<IdentityUser, IdentityRole>();
     services.AddInstance<IRoleStore<IdentityRole>>(new RoleStore<IdentityRole>(context));
     return services.BuildServiceProvider().GetRequiredService<RoleManager<IdentityRole>>();
 }
开发者ID:stormwild,项目名称:Identity,代码行数:7,代码来源:TestIdentityFactory.cs

示例13: TestHelloNonGenericServiceDecoratorNoInterface

        public void TestHelloNonGenericServiceDecoratorNoInterface()
        {
            var services = new ServiceCollection();

            services.AddInstance<IHelloService>(new HelloService());

            services.AddSingleton<IHelloService>(sp => new HelloService());
            services.AddScoped<IHelloService>(sp => new HelloService());
            services.AddTransient<IHelloService>(sp => new HelloService());

            services.AddSingleton<IHelloService, HelloService>();
            services.AddScoped<IHelloService, HelloService>();
            services.AddTransient<IHelloService, HelloService>();

            services.AddDecorator(typeof(IHelloService), (sp, s) => new HelloServiceDecoratorNoInterface((IHelloService)s));

            var provider = services.BuildServiceProvider();

            var helloServices = provider.GetRequiredServices<IHelloService>();
            Assert.NotNull(helloServices);
            var collection = helloServices as IHelloService[] ?? helloServices.ToArray();
            Assert.Equal(7, collection.Length);
            Assert.NotEmpty(collection);
            foreach (var helloService in collection)
            {
                Assert.NotNull(helloService);
                Assert.Equal("Decorated without interface: Hello world.", helloService.SayHello("world"));
            }
        }
开发者ID:sherif-elmetainy,项目名称:DI,代码行数:29,代码来源:DecoratorTests.cs

示例14: OnValidateIdentityRejectsWhenValidateSecurityStampFails

        public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
        {
            var user = new IdentityUser("test");
            var httpContext = new Mock<HttpContext>();
            var userManager = MockHelpers.MockUserManager<IdentityUser>();
            var authManager = new Mock<IAuthenticationManager>();
            var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>();
            var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object,
                authManager.Object, claimsManager.Object);
            signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(signInManager.Object);
            httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow });
            var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Identity);
            await
                SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context);
            Assert.Null(context.Identity);
            signInManager.VerifyAll();
        }
开发者ID:ChMar,项目名称:Identity,代码行数:26,代码来源:SecurityStampValidatorTest.cs

示例15: Main

        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);
            
            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            serviceCollection.AddInstance<IHostingEnvironment>(new HostingEnvironment() { WebRoot = "wwwroot" });
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
开发者ID:rvfvazquez,项目名称:BugTracker,代码行数:33,代码来源:Program.cs


注:本文中的Microsoft.Framework.DependencyInjection.ServiceCollection.AddInstance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。