本文整理汇总了C#中SimpleInjector.Container.GetAllInstances方法的典型用法代码示例。如果您正苦于以下问题:C# Container.GetAllInstances方法的具体用法?C# Container.GetAllInstances怎么用?C# Container.GetAllInstances使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimpleInjector.Container
的用法示例。
在下文中一共展示了Container.GetAllInstances方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RegisterServices
public static void RegisterServices(Container container, ILoggerFactory loggerFactory) {
container.RegisterSingleton<ILoggerFactory>(loggerFactory);
container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>));
ServiceProvider.Current = container;
container.RegisterSingleton<ISerializer>(() => new JsonNetSerializer());
var metricsClient = new InMemoryMetricsClient();
container.RegisterSingleton<IMetricsClient>(metricsClient);
container.RegisterSingleton<ICacheClient, InMemoryCacheClient>();
container.RegisterCollection(typeof(IQueueBehavior<ValuesPost>), new[] {
Lifestyle.Singleton.CreateRegistration(
() => new MetricsQueueBehavior<ValuesPost>(metricsClient), container)
});
container.RegisterSingleton<IQueue<ValuesPost>>(() => new InMemoryQueue<ValuesPost>(behaviors: container.GetAllInstances<IQueueBehavior<ValuesPost>>()));
container.RegisterCollection(typeof(IQueueBehavior<WorkItemData>), new[] {
Lifestyle.Singleton.CreateRegistration(
() => new MetricsQueueBehavior<WorkItemData>(metricsClient), container)
});
var handlers = new WorkItemHandlers();
handlers.Register<DeleteValueWorkItem, DeleteValueWorkItemHandler>();
container.RegisterSingleton(handlers);
container.RegisterSingleton<IQueue<WorkItemData>>(() => new InMemoryQueue<WorkItemData>(behaviors: container.GetAllInstances<IQueueBehavior<WorkItemData>>(), workItemTimeout: TimeSpan.FromHours(1)));
container.RegisterSingleton<IMessageBus, InMemoryMessageBus>();
container.RegisterSingleton<IMessagePublisher>(container.GetInstance<IMessageBus>);
container.RegisterSingleton<IMessageSubscriber>(container.GetInstance<IMessageBus>);
container.RegisterSingleton<ILockProvider, CacheLockProvider>();
container.RegisterSingleton<IFileStorage>(new InMemoryFileStorage());
}
示例2: RegisterDependencies
public static void RegisterDependencies()
{
var container = new Container {Options = {DefaultScopedLifestyle = new WebRequestLifestyle()}};
// Container
container.Register<IServiceProvider>(() => container);
// Request (command/query) dispatcher
container.Register<IRequestDispatcher, RequestDispatcher>();
// Command handlers
container.Register(typeof (ICommandHandler<>), new[] {typeof (TabService).Assembly});
container.RegisterDecorator(typeof (ICommandHandler<>), typeof (ValidationDecoratorCommandHandler<>));
container.RegisterDecorator(typeof (ICommandHandler<>), typeof (LoggingDecoratorCommandHandler<>));
// Query handlers
container.Register(typeof (IQueryHandler<,>), new[] {typeof (TabReadModel).Assembly});
// Validators
container.RegisterSingleton(typeof (IValidator<>), typeof (CompositeValidator<>));
container.AppendToCollection(typeof (IValidator<>), typeof (DataAnnotationsValidator<>));
container.RegisterCollection(typeof (IValidator<>), typeof (MvcApplication).Assembly);
// Data annotations validators
container.Register(typeof (IValidationAttributeValidator<>), new[] {typeof (IValidationAttributeValidator<>).Assembly});
// Loggers
container.RegisterSingleton<ILoggerFactory, NLogLoggerFactory>();
// Action filters
container.RegisterCollection(typeof (IActionFilter<>), typeof (MvcApplication).Assembly);
// Repository
container.Register<IEventStore, InMemoryEventStore>();
// Aggregate factory
container.Register<IAggregateFactory, AggregateFactory>();
// Event publisher
container.Register<IEventPublisher>(() => new EventPublisher(type => container.GetAllInstances(type), container.GetInstance<ILoggerFactory>()));
// Event handlers
container.RegisterCollection(typeof (IEventSubscriber<>), new[] {typeof (TabReadModel).Assembly});
// View model database
container.RegisterSingleton<IReadModelDatabase, InMemoryReadModelDatabase>();
// Verify
container.Verify();
System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
System.Web.Mvc.GlobalFilters.Filters.Add(new ActionFilterDispatcher(type => container.GetAllInstances(type)));
ServiceProvider = container;
}
示例3: PopulateProviderCache
private void PopulateProviderCache()
{
if (this.Providers == null)
{
this.Providers = new Dictionary<string, IAuditDbProvider>();
}
string providerDirectory = AppDomain.CurrentDomain.BaseDirectory;
var providerAssemblies =
from file in new DirectoryInfo(providerDirectory).GetFiles()
where file.Extension.ToLower() == ".dll"
select Assembly.LoadFile(file.FullName);
Container container = new Container();
var providerTypes = container.GetTypesToRegister(typeof(IAuditDbProvider), providerAssemblies);
container.RegisterCollection<IAuditDbProvider>(providerTypes);
foreach (var provider in container.GetAllInstances<IAuditDbProvider>())
{
Providers.Add(provider.ProviderNamespace.ToLowerInvariant(),provider);
}
}
示例4: OnStart
/// <summary>
/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control
/// Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to
/// take when the service starts.
/// </summary>
/// <param name="args">Data passed by the Start command.</param>
protected override void OnStart(string[] args)
{
_logger.InfoFormat("Starting {0} (v{1}) service.", ApplicationParameters.Name, ApplicationParameters.ProductVersion);
try
{
//AutoMapperInitializer.Initialize();
SimpleInjectorContainer.start();
_container = SimpleInjectorContainer.Container;
_subscription = EventManager.subscribe<ShutdownMessage>((message) => OnStop(), null, null);
var fileSystem = _container.GetInstance<IFileSystem>();
fileSystem.create_directory_if_not_exists(".\\files");
var tasks = _container.GetAllInstances<ITask>();
foreach (var task in tasks)
{
task.initialize();
}
_logger.InfoFormat("{0} service is now operational.", ApplicationParameters.Name);
if ((args.Length > 0) && (Array.IndexOf(args, "/console") != -1))
{
Console.WriteLine("Press Control+C to exit.");
// all of these options have their own issues.
//do
//{
// Thread.Sleep(900000);
//}
//while (1==1);
// http://stackoverflow.com/a/16218470/18475
manualReset.WaitOne();
// this causes process calls (like calls to vagrant) to hang.
//Console.ReadKey();
}
}
catch (Exception ex)
{
_logger.ErrorFormat(
"{0} service had an error on {1} (with user {2}):{3}{4}",
ApplicationParameters.Name,
Environment.MachineName,
Environment.UserName,
Environment.NewLine,
ex);
}
}
示例5: Setup
public static void Setup()
{
var container = new Container();
var perRequest = new WebRequestLifestyle();
var dataAccessAssembly = typeof(CinemaContext).Assembly;
var moviesAssembly = typeof(Seat).Assembly;
var promotionsAssembly = typeof(Promotions.Promotion).Assembly;
var applicationAssembly = typeof(RenamePromotionCommand).Assembly;
var connectionString = ConfigurationManager.ConnectionStrings["DDDCinema"].ConnectionString;
container.Register(() => new CinemaContext(connectionString), perRequest);
container.Register(() => new PromotionsContext(connectionString), perRequest);
container.Register(() => new InfrastructureContext(connectionString), perRequest);
container.Register(() => new DDDCinemaReadonly(), perRequest);
var userProviderRegistration = Lifestyle.Singleton.CreateRegistration<ContextUserProvider>(container);
container.AddRegistration(typeof(ICurrentUserProvider), userProviderRegistration);
container.AddRegistration(typeof(ContextUserProvider), userProviderRegistration);
container.Register<IWinChanceCalculatorFactory, SimpleInjectorWinChanceCalculatorFactory>(Lifestyle.Singleton);
foreach (var repositorType in dataAccessAssembly.GetExportedTypes()
.Where(t => t.Name.Contains("Repository")))
{
container.Register(repositorType.GetInterfaces().Single(), repositorType, perRequest);
}
container.RegisterDecorator(typeof(ICommandHandler<LoginCommand>), typeof(AuditingLoginCommandHandler));
container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuditingCommandHandler<>),
p => !p.AppliedDecorators.Any(t => t.Name.Contains("Auditing")));
container.RegisterDecorator(typeof(ICommandHandler<>), typeof(CinemaTransactionalCommandHandler<>));
container.RegisterDecorator(typeof(ICommandHandler<>), typeof(PromotionTransactionalCommandHandler<>));
container.RegisterDecorator(typeof(ICommandHandler<>), typeof(InfrastructureTransactionalCommandHandler<>));
container.Register(typeof(ICommandHandler<>), new[] { applicationAssembly });
container.RegisterCollection(typeof(INotificationSender), new[] { moviesAssembly });
var registration = perRequest.CreateRegistration<SendNotificationWhenSeatTaken>(container);
container.AppendToCollection(typeof(IDomainEventHandler<>), typeof(AuditOccurrenceEventHandler<>));
container.RegisterCollection(typeof(IDomainEventHandler<>), moviesAssembly, promotionsAssembly);
container.RegisterDecorator(typeof(IDomainEventHandler<>), typeof(AuditingEventHandler<>),
p => !p.ImplementationType.Name.Contains("Audit"));
container.Register<List<INotificationSender>>(() => container.GetAllInstances<INotificationSender>().ToList(), perRequest);
container.Register<ISheduler, SagaTimeoutSheduler>(perRequest);
container.Register<IPromotionCodeGenerator, PromoCodeGenerator>(perRequest);
DomainEventBus.Current = new SimpleInjectorEventBus(container);
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
示例6: RegisterMapper
/// <summary>
/// Registers the mapper.
/// </summary>
/// <param name="container">The container.</param>
public static void RegisterMapper(Container container)
{
try
{
AutoMapper.Mapper.Initialize(mapper =>
{
IEnumerable<Profile> profiles = container.GetAllInstances<Profile>();
foreach (Profile profile in profiles)
{
mapper.AddProfile(profile);
}
});
Mapper.AssertConfigurationIsValid();
}
catch (Exception ex)
{
ex.ExceptionValueTracker(container);
}
}
示例7: RegisterServices
public void RegisterServices(Container container) {
Logger.RegisterWriter(new NLogAdapter());
if (Settings.Current.EnableMetricsReporting)
container.RegisterSingleton<IMetricsClient>(() => new StatsDMetricsClient(Settings.Current.MetricsServerName, Settings.Current.MetricsServerPort, "ex"));
else
Log.Warn().Message("StatsD Metrics is NOT enabled.").Write();
if (Settings.Current.EnableRedis) {
container.RegisterSingleton<ConnectionMultiplexer>(() => {
var multiplexer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionString);
multiplexer.PreserveAsyncOrder = false;
return multiplexer;
});
container.RegisterSingleton<ICacheClient, RedisHybridCacheClient>();
container.RegisterSingleton<IQueue<EventPost>>(() => new RedisQueue<EventPost>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>(), behaviors: container.GetAllInstances<IQueueBehavior<EventPost>>()));
container.RegisterSingleton<IQueue<EventUserDescription>>(() => new RedisQueue<EventUserDescription>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>(), behaviors: container.GetAllInstances<IQueueBehavior<EventUserDescription>>()));
container.RegisterSingleton<IQueue<EventNotificationWorkItem>>(() => new RedisQueue<EventNotificationWorkItem>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>(), behaviors: container.GetAllInstances<IQueueBehavior<EventNotificationWorkItem>>()));
container.RegisterSingleton<IQueue<WebHookNotification>>(() => new RedisQueue<WebHookNotification>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>(), behaviors: container.GetAllInstances<IQueueBehavior<WebHookNotification>>()));
container.RegisterSingleton<IQueue<MailMessage>>(() => new RedisQueue<MailMessage>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>(), behaviors: container.GetAllInstances<IQueueBehavior<MailMessage>>()));
container.RegisterSingleton<IQueue<StatusMessage>>(() => new RedisQueue<StatusMessage>(container.GetInstance<ConnectionMultiplexer>(), container.GetInstance<ISerializer>()));
container.RegisterSingleton<IQueue<WorkItemData>>(() => new RedisQueue<WorkItemData>(container.GetInstance<ConnectionMultiplexer>(), workItemTimeout: TimeSpan.FromHours(1), behaviors: container.GetAllInstances<IQueueBehavior<WorkItemData>>()));
container.RegisterSingleton<IMessageBus>(() => new RedisMessageBus(container.GetInstance<ConnectionMultiplexer>().GetSubscriber(), serializer: container.GetInstance<ISerializer>()));
} else {
Log.Warn().Message("Redis is NOT enabled.").Write();
}
if (Settings.Current.EnableAzureStorage)
container.RegisterSingleton<IFileStorage>(new AzureFileStorage(Settings.Current.AzureStorageConnectionString, "ex-events"));
else
Log.Warn().Message("Azure Storage is NOT enabled.").Write();
var client = ExceptionlessClient.Default;
container.RegisterSingleton<ICoreLastReferenceIdManager, ExceptionlessClientCoreLastReferenceIdManager>();
container.RegisterSingleton<ExceptionlessClient>(() => client);
client.Configuration.SetVersion(Settings.Current.Version);
client.Register();
container.AddBootstrapper<HttpConfiguration>(config => client.RegisterWebApi(config));
client.Configuration.UseInMemoryStorage();
client.Configuration.UseReferenceIds();
}
示例8: SetUp
public static void SetUp(Container container)
{
bool securityTrimmingEnabled = false;
bool enableLocalization = true;
string absoluteFileName = HostingEnvironment.MapPath("~/Mvc.sitemap");
TimeSpan absoluteCacheExpiration = TimeSpan.FromMinutes(5);
string[] includeAssembliesForScan = new string[] { "$AssemblyName$" };
// Extension to allow resolution of arrays by GetAllInstances (natively based on IEnumerable).
// source from: https://simpleinjector.codeplex.com/wikipage?title=CollectionRegistrationExtensions
AllowToResolveArraysAndLists(container);
var currentAssembly = typeof(MvcSiteMapProviderContainerInitializer).Assembly;
var siteMapProviderAssembly = typeof(SiteMaps).Assembly;
var allAssemblies = new Assembly[] { currentAssembly, siteMapProviderAssembly };
var excludeTypes = new Type[]
{
typeof (SiteMapNodeVisibilityProviderStrategy),
typeof (SiteMapXmlReservedAttributeNameProvider),
typeof (SiteMapBuilderSetStrategy),
typeof (ControllerTypeResolverFactory),
// Added 2013-06-28 by eric-b to avoid default singleton registration:
typeof(XmlSiteMapController),
// Added 2013-06-28 by eric-b for SimpleInjector.Verify method:
typeof(PreservedRouteParameterCollection),
typeof(MvcResolver),
typeof(MvcSiteMapProvider.SiteMap),
typeof(MetaRobotsValueCollection),
typeof(RoleCollection),
typeof(SiteMapPluginProvider),
typeof(ControllerTypeResolver),
typeof(RouteValueDictionary),
typeof(AttributeDictionary)
};
var multipleImplementationTypes = new Type[]
{
typeof (ISiteMapNodeUrlResolver),
typeof (ISiteMapNodeVisibilityProvider),
typeof (IDynamicNodeProvider)
};
// Single implementations of interface with matching name (minus the "I").
CommonConventions.RegisterDefaultConventions(
(interfaceType, implementationType) => container.RegisterSingle(interfaceType, implementationType),
new Assembly[] { siteMapProviderAssembly },
allAssemblies,
excludeTypes,
string.Empty);
// Multiple implementations of strategy based extension points
CommonConventions.RegisterAllImplementationsOfInterfaceSingle(
(interfaceType, implementationTypes) => container.RegisterAll(interfaceType, implementationTypes),
multipleImplementationTypes,
allAssemblies,
new Type[0],
"^Composite");
container.Register<XmlSiteMapController>();
// Visibility Providers
container.RegisterSingle<ISiteMapNodeVisibilityProviderStrategy>(() =>
new SiteMapNodeVisibilityProviderStrategy(
container.GetAllInstances
<ISiteMapNodeVisibilityProvider>().
ToArray(), string.Empty));
// Pass in the global controllerBuilder reference
container.RegisterSingle<ControllerBuilder>(() => ControllerBuilder.Current);
container.RegisterSingle<IControllerBuilder, ControllerBuilderAdaptor>();
container.RegisterSingle<IBuildManager, BuildManagerAdaptor>();
container.RegisterSingle<IControllerTypeResolverFactory>(() =>
new ControllerTypeResolverFactory(new string[0],
container.GetInstance
<IControllerBuilder
>(),
container.GetInstance
<IBuildManager>()));
// Configure Security
container.RegisterSingle<AuthorizeAttributeAclModule>(() => new AuthorizeAttributeAclModule(
container.GetInstance<IMvcContextFactory>(),
container.GetInstance<IObjectCopier>(),
container.GetInstance<IControllerDescriptorFactory>(),
container.GetInstance<IControllerBuilder>(),
container.GetInstance<IAuthorizeAttributeBuilder>(),
container.GetInstance<IGlobalFilterProvider>()));
container.RegisterAll<IAclModule>(typeof(AuthorizeAttributeAclModule), typeof(XmlRolesAclModule));
container.RegisterSingle<IAclModule>(() => new CompositeAclModule(container.GetAllInstances<IAclModule>().ToArray()));
// Setup cache
#if NET35
container.RegisterSingleOpenGeneric(typeof(ICacheProvider<>), typeof(AspNetCacheProvider<>));
container.RegisterSingle<ICacheDependency>(() => new AspNetFileCacheDependency(absoluteFileName));
#else
//.........这里部分代码省略.........
示例9: RegisterServices
public static void RegisterServices(Container container, ILoggerFactory loggerFactory) {
container.RegisterLogger(loggerFactory);
container.RegisterSingleton<IDependencyResolver>(() => new SimpleInjectorDependencyResolver(container));
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
DateParseHandling = DateParseHandling.DateTimeOffset
};
var contractResolver = new ExceptionlessContractResolver();
contractResolver.UseDefaultResolverFor(typeof(DataDictionary), typeof(SettingsDictionary), typeof(VersionOne.VersionOneWebHookStack), typeof(VersionOne.VersionOneWebHookEvent));
var settings = new JsonSerializerSettings {
MissingMemberHandling = MissingMemberHandling.Ignore,
DateParseHandling = DateParseHandling.DateTimeOffset,
ContractResolver = contractResolver
};
settings.AddModelConverters(loggerFactory.CreateLogger(nameof(Bootstrapper)));
container.RegisterSingleton<IContractResolver>(() => contractResolver);
container.RegisterSingleton<JsonSerializerSettings>(settings);
container.RegisterSingleton<JsonSerializer>(JsonSerializer.Create(settings));
container.RegisterSingleton<ISerializer>(() => new JsonNetSerializer(settings));
container.RegisterSingleton<IMetricsClient>(() => new InMemoryMetricsClient(loggerFactory: loggerFactory));
container.RegisterSingleton<QueryBuilderRegistry>(() => {
var builder = new QueryBuilderRegistry();
builder.RegisterDefaults();
builder.Register(new OrganizationIdQueryBuilder());
builder.Register(new ProjectIdQueryBuilder());
builder.Register(new StackIdQueryBuilder());
return builder;
});
container.RegisterSingleton<ElasticConfigurationBase, ElasticConfiguration>();
container.RegisterSingleton<IElasticClient>(() => container.GetInstance<ElasticConfigurationBase>().GetClient(Settings.Current.ElasticSearchConnectionString.Split(',').Select(url => new Uri(url))));
container.RegisterSingleton<EventIndex, EventIndex>();
container.RegisterSingleton<OrganizationIndex, OrganizationIndex>();
container.RegisterSingleton<StackIndex, StackIndex>();
container.RegisterSingleton<ICacheClient, InMemoryCacheClient>();
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventPost>>>(() => new[] { new MetricsQueueBehavior<EventPost>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventUserDescription>>>(() => new[] { new MetricsQueueBehavior<EventUserDescription>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventNotificationWorkItem>>>(() => new[] { new MetricsQueueBehavior<EventNotificationWorkItem>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<WebHookNotification>>>(() => new[] { new MetricsQueueBehavior<WebHookNotification>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<MailMessage>>>(() => new[] { new MetricsQueueBehavior<MailMessage>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<WorkItemData>>>(() => new[] { new MetricsQueueBehavior<WorkItemData>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IQueue<EventPost>>(() => new InMemoryQueue<EventPost>(behaviors: container.GetAllInstances<IQueueBehavior<EventPost>>()));
container.RegisterSingleton<IQueue<EventUserDescription>>(() => new InMemoryQueue<EventUserDescription>(behaviors: container.GetAllInstances<IQueueBehavior<EventUserDescription>>()));
container.RegisterSingleton<IQueue<EventNotificationWorkItem>>(() => new InMemoryQueue<EventNotificationWorkItem>(behaviors: container.GetAllInstances<IQueueBehavior<EventNotificationWorkItem>>()));
container.RegisterSingleton<IQueue<WebHookNotification>>(() => new InMemoryQueue<WebHookNotification>(behaviors: container.GetAllInstances<IQueueBehavior<WebHookNotification>>()));
container.RegisterSingleton<IQueue<MailMessage>>(() => new InMemoryQueue<MailMessage>(behaviors: container.GetAllInstances<IQueueBehavior<MailMessage>>()));
var workItemHandlers = new WorkItemHandlers();
workItemHandlers.Register<ReindexWorkItem>(container.GetInstance<ReindexWorkItemHandler>);
workItemHandlers.Register<RemoveOrganizationWorkItem>(container.GetInstance<RemoveOrganizationWorkItemHandler>);
workItemHandlers.Register<RemoveProjectWorkItem>(container.GetInstance<RemoveProjectWorkItemHandler>);
workItemHandlers.Register<SetLocationFromGeoWorkItem>(container.GetInstance<SetLocationFromGeoWorkItemHandler>);
workItemHandlers.Register<SetProjectIsConfiguredWorkItem>(container.GetInstance<SetProjectIsConfiguredWorkItemHandler>);
workItemHandlers.Register<StackWorkItem>(container.GetInstance<StackWorkItemHandler>);
workItemHandlers.Register<ThrottleBotsWorkItem>(container.GetInstance<ThrottleBotsWorkItemHandler>);
workItemHandlers.Register<OrganizationMaintenanceWorkItem>(container.GetInstance<OrganizationMaintenanceWorkItemHandler>);
workItemHandlers.Register<OrganizationNotificationWorkItem>(container.GetInstance<OrganizationNotificationWorkItemHandler>);
workItemHandlers.Register<ProjectMaintenanceWorkItem>(container.GetInstance<ProjectMaintenanceWorkItemHandler>);
container.RegisterSingleton<WorkItemHandlers>(workItemHandlers);
container.RegisterSingleton<IQueue<WorkItemData>>(() => new InMemoryQueue<WorkItemData>(behaviors: container.GetAllInstances<IQueueBehavior<WorkItemData>>(), workItemTimeout: TimeSpan.FromHours(1)));
container.RegisterSingleton<IMessageBus, InMemoryMessageBus>();
container.RegisterSingleton<IMessagePublisher>(container.GetInstance<IMessageBus>);
container.RegisterSingleton<IMessageSubscriber>(container.GetInstance<IMessageBus>);
if (!String.IsNullOrEmpty(Settings.Current.StorageFolder))
container.RegisterSingleton<IFileStorage>(new FolderFileStorage(Settings.Current.StorageFolder));
else
container.RegisterSingleton<IFileStorage>(new InMemoryFileStorage());
container.RegisterSingleton<IStackRepository, StackRepository>();
container.RegisterSingleton<IEventRepository, EventRepository>();
container.RegisterSingleton<IOrganizationRepository, OrganizationRepository>();
container.RegisterSingleton<IProjectRepository, ProjectRepository>();
container.RegisterSingleton<IUserRepository, UserRepository>();
container.RegisterSingleton<IWebHookRepository, WebHookRepository>();
container.RegisterSingleton<ITokenRepository, TokenRepository>();
container.RegisterSingleton<IApplicationRepository, ApplicationRepository>();
container.RegisterSingleton<IGeoIpService, MaxMindGeoIpService>();
container.RegisterSingleton<IGeocodeService, NullGeocodeService>();
container.Register(typeof(IValidator<>), new[] { typeof(Bootstrapper).Assembly }, Lifestyle.Singleton);
container.Register(typeof(ElasticRepositoryContext<>), typeof(ElasticRepositoryContext<>), Lifestyle.Singleton);
container.RegisterSingleton<IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates"));
container.RegisterSingleton<IMailer, Mailer>();
if (Settings.Current.WebsiteMode != WebsiteMode.Dev)
container.RegisterSingleton<IMailSender, SmtpMailSender>();
else
//.........这里部分代码省略.........
示例10: SetUp
public static void SetUp(Container container)
{
bool enableLocalization = true;
string absoluteFileName = HostingEnvironment.MapPath("~/Mvc.sitemap");
TimeSpan absoluteCacheExpiration = TimeSpan.FromMinutes(5);
bool visibilityAffectsDescendants = true;
bool useTitleIfDescriptionNotProvided = true;
#if Demo
// Settings for MvcMusicStore demo: don't copy into your project
bool securityTrimmingEnabled = true;
string[] includeAssembliesForScan = new string[] { "Mvc Music Store" };
#else
bool securityTrimmingEnabled = false;
string[] includeAssembliesForScan = new string[] { "$AssemblyName$" };
#endif
// Extension to allow resolution of arrays by GetAllInstances (natively based on IEnumerable).
// source from: https://simpleinjector.codeplex.com/wikipage?title=CollectionRegistrationExtensions
AllowToResolveArraysAndLists(container);
var currentAssembly = typeof(MvcSiteMapProviderContainerInitializer).Assembly;
var siteMapProviderAssembly = typeof(SiteMaps).Assembly;
var allAssemblies = new Assembly[] { currentAssembly, siteMapProviderAssembly };
var excludeTypes = new Type[]
{
// Use this array to add types you wish to explicitly exclude from convention-based
// auto-registration. By default all types that either match I[TypeName] = [TypeName] or
// I[TypeName] = [TypeName]Adapter will be automatically wired up as long as they don't
// have the [ExcludeFromAutoRegistrationAttribute].
//
// If you want to override a type that follows the convention, you should add the name
// of either the implementation name or the interface that it inherits to this list and
// add your manual registration code below. This will prevent duplicate registrations
// of the types from occurring.
// Example:
// typeof(SiteMap),
// typeof(SiteMapNodeVisibilityProviderStrategy)
};
var multipleImplementationTypes = new Type[]
{
typeof(ISiteMapNodeUrlResolver),
typeof(ISiteMapNodeVisibilityProvider),
typeof(IDynamicNodeProvider)
};
// Matching type name (I[TypeName] = [TypeName]) or matching type name + suffix Adapter (I[TypeName] = [TypeName]Adapter)
// and not decorated with the [ExcludeFromAutoRegistrationAttribute].
CommonConventions.RegisterDefaultConventions(
(interfaceType, implementationType) => container.RegisterSingle(interfaceType, implementationType),
new Assembly[] { siteMapProviderAssembly },
allAssemblies,
excludeTypes,
string.Empty);
// Multiple implementations of strategy based extension points (and not decorated with [ExcludeFromAutoRegistrationAttribute]).
CommonConventions.RegisterAllImplementationsOfInterfaceSingle(
(interfaceType, implementationTypes) => container.RegisterAll(interfaceType, implementationTypes),
multipleImplementationTypes,
allAssemblies,
excludeTypes,
string.Empty);
container.Register<XmlSiteMapController>();
// Visibility Providers
container.RegisterSingle<ISiteMapNodeVisibilityProviderStrategy>(() =>
new SiteMapNodeVisibilityProviderStrategy(
container.GetAllInstances<ISiteMapNodeVisibilityProvider>().ToArray(), string.Empty));
// Pass in the global controllerBuilder reference
container.RegisterSingle<ControllerBuilder>(() => ControllerBuilder.Current);
container.RegisterSingle<IControllerTypeResolverFactory>(() =>
new ControllerTypeResolverFactory(
new string[0],
container.GetInstance<IControllerBuilder>(),
container.GetInstance<IBuildManager>()));
// Configure Security
container.RegisterAll<IAclModule>(typeof(AuthorizeAttributeAclModule), typeof(XmlRolesAclModule));
container.RegisterSingle<IAclModule>(() => new CompositeAclModule(container.GetAllInstances<IAclModule>().ToArray()));
// Setup cache
#if NET35
container.RegisterSingleOpenGeneric(typeof(ICacheProvider<>), typeof(AspNetCacheProvider<>));
container.RegisterSingle<ICacheDependency>(() => new AspNetFileCacheDependency(absoluteFileName));
#else
container.RegisterSingle<System.Runtime.Caching.ObjectCache>(() => System.Runtime.Caching.MemoryCache.Default);
container.RegisterSingleOpenGeneric(typeof(ICacheProvider<>), typeof(RuntimeCacheProvider<>));
container.RegisterSingle<ICacheDependency>(() => new RuntimeFileCacheDependency(absoluteFileName));
#endif
container.RegisterSingle<ICacheDetails>(() => new CacheDetails(absoluteCacheExpiration, TimeSpan.MinValue, container.GetInstance<ICacheDependency>()));
// Configure the visitors
container.RegisterSingle<ISiteMapNodeVisitor, UrlResolvingSiteMapNodeVisitor>();
// Prepare for the sitemap node providers
container.RegisterSingle<IReservedAttributeNameProvider>(() => new ReservedAttributeNameProvider(new string[0]));
container.RegisterSingle<IXmlSource>(() => new FileXmlSource(absoluteFileName));
//.........这里部分代码省略.........
示例11: RegisterServices
public void RegisterServices(Container container) {
// Foundation service provider
ServiceProvider.Current = container;
container.RegisterSingleton<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
DateParseHandling = DateParseHandling.DateTimeOffset
};
var contractResolver = new ExceptionlessContractResolver();
contractResolver.UseDefaultResolverFor(typeof(DataDictionary), typeof(SettingsDictionary), typeof(VersionOne.VersionOneWebHookStack), typeof(VersionOne.VersionOneWebHookEvent));
var settings = new JsonSerializerSettings {
MissingMemberHandling = MissingMemberHandling.Ignore,
DateParseHandling = DateParseHandling.DateTimeOffset,
ContractResolver = contractResolver
};
settings.AddModelConverters();
container.RegisterSingleton<IContractResolver>(() => contractResolver);
container.RegisterSingleton<JsonSerializerSettings>(settings);
container.RegisterSingleton<JsonSerializer>(JsonSerializer.Create(settings));
container.RegisterSingleton<ISerializer>(() => new JsonNetSerializer(settings));
var metricsClient = new InMemoryMetricsClient();
metricsClient.StartDisplayingStats();
container.RegisterSingleton<IMetricsClient>(metricsClient);
container.RegisterSingleton<IElasticClient>(() => container.GetInstance<ElasticSearchConfiguration>().GetClient(Settings.Current.ElasticSearchConnectionString.Split(',').Select(url => new Uri(url))));
container.RegisterSingleton<EventIndex, EventIndex>();
container.RegisterSingleton<OrganizationIndex, OrganizationIndex>();
container.RegisterSingleton<StackIndex, StackIndex>();
container.RegisterSingleton<ICacheClient, InMemoryCacheClient>();
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventPost>>>(() => new[] { new MetricsQueueBehavior<EventPost>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventUserDescription>>>(() => new[] { new MetricsQueueBehavior<EventUserDescription>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<EventNotificationWorkItem>>>(() => new[] { new MetricsQueueBehavior<EventNotificationWorkItem>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<WebHookNotification>>>(() => new[] { new MetricsQueueBehavior<WebHookNotification>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<MailMessage>>>(() => new[] { new MetricsQueueBehavior<MailMessage>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IEnumerable<IQueueBehavior<WorkItemData>>>(() => new[] { new MetricsQueueBehavior<WorkItemData>(container.GetInstance<IMetricsClient>()) });
container.RegisterSingleton<IQueue<EventPost>>(() => new InMemoryQueue<EventPost>(behaviors: container.GetAllInstances<IQueueBehavior<EventPost>>()));
container.RegisterSingleton<IQueue<EventUserDescription>>(() => new InMemoryQueue<EventUserDescription>(behaviors: container.GetAllInstances<IQueueBehavior<EventUserDescription>>()));
container.RegisterSingleton<IQueue<EventNotificationWorkItem>>(() => new InMemoryQueue<EventNotificationWorkItem>(behaviors: container.GetAllInstances<IQueueBehavior<EventNotificationWorkItem>>()));
container.RegisterSingleton<IQueue<WebHookNotification>>(() => new InMemoryQueue<WebHookNotification>(behaviors: container.GetAllInstances<IQueueBehavior<WebHookNotification>>()));
container.RegisterSingleton<IQueue<MailMessage>>(() => new InMemoryQueue<MailMessage>(behaviors: container.GetAllInstances<IQueueBehavior<MailMessage>>()));
container.RegisterSingleton<IQueue<StatusMessage>>(() => new InMemoryQueue<StatusMessage>());
var workItemHandlers = new WorkItemHandlers();
workItemHandlers.Register<ReindexWorkItem, ReindexWorkItemHandler>();
workItemHandlers.Register<RemoveOrganizationWorkItem, RemoveOrganizationWorkItemHandler>();
workItemHandlers.Register<RemoveProjectWorkItem, RemoveProjectWorkItemHandler>();
workItemHandlers.Register<StackWorkItem, StackWorkItemHandler>();
workItemHandlers.Register<ThrottleBotsWorkItem, ThrottleBotsWorkItemHandler>();
container.RegisterSingleton<WorkItemHandlers>(workItemHandlers);
container.RegisterSingleton<IQueue<WorkItemData>>(() => new InMemoryQueue<WorkItemData>(behaviors: container.GetAllInstances<IQueueBehavior<WorkItemData>>(), workItemTimeout: TimeSpan.FromHours(1)));
container.RegisterSingleton<IMessageBus, InMemoryMessageBus>();
container.RegisterSingleton<IMessagePublisher>(container.GetInstance<IMessageBus>);
container.RegisterSingleton<IMessageSubscriber>(container.GetInstance<IMessageBus>);
if (!String.IsNullOrEmpty(Settings.Current.StorageFolder))
container.RegisterSingleton<IFileStorage>(new FolderFileStorage(Settings.Current.StorageFolder));
else
container.RegisterSingleton<IFileStorage>(new InMemoryFileStorage());
container.RegisterSingleton<IStackRepository, StackRepository>();
container.RegisterSingleton<IEventRepository, EventRepository>();
container.RegisterSingleton<IOrganizationRepository, OrganizationRepository>();
container.RegisterSingleton<IProjectRepository, ProjectRepository>();
container.RegisterSingleton<IUserRepository, UserRepository>();
container.RegisterSingleton<IWebHookRepository, WebHookRepository>();
container.RegisterSingleton<ITokenRepository, TokenRepository>();
container.RegisterSingleton<IApplicationRepository, ApplicationRepository>();
container.RegisterSingleton<IGeoIPResolver, MindMaxGeoIPResolver>();
container.RegisterSingleton<IValidator<Application>, ApplicationValidator>();
container.RegisterSingleton<IValidator<Organization>, OrganizationValidator>();
container.RegisterSingleton<IValidator<PersistentEvent>, PersistentEventValidator>();
container.RegisterSingleton<IValidator<Project>, ProjectValidator>();
container.RegisterSingleton<IValidator<Stack>, StackValidator>();
container.RegisterSingleton<IValidator<Models.Token>, TokenValidator>();
container.RegisterSingleton<IValidator<UserDescription>, UserDescriptionValidator>();
container.RegisterSingleton<IValidator<User>, UserValidator>();
container.RegisterSingleton<IValidator<WebHook>, WebHookValidator>();
container.RegisterSingleton<IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates"));
container.RegisterSingleton<IMailer, Mailer>();
if (Settings.Current.WebsiteMode != WebsiteMode.Dev)
container.RegisterSingleton<IMailSender, SmtpMailSender>();
else
container.RegisterSingleton<IMailSender>(() => new InMemoryMailSender());
container.RegisterSingleton<ILockProvider, CacheLockProvider>();
container.Register<StripeEventHandler>();
container.RegisterSingleton<BillingManager>();
container.RegisterSingleton<DataHelper>();
container.RegisterSingleton<EventStats>();
//.........这里部分代码省略.........