本文整理汇总了C#中SimpleInjector.Container.GetInstance方法的典型用法代码示例。如果您正苦于以下问题:C# Container.GetInstance方法的具体用法?C# Container.GetInstance怎么用?C# Container.GetInstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimpleInjector.Container
的用法示例。
在下文中一共展示了Container.GetInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Initialize
public static void Initialize()
{
var config = GlobalConfiguration.Configuration;
var container = new Container();
container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
Configure(container);
try
{
container.Verify();
}
catch (Exception e)
{
Trace.TraceError("Failed to initialize IoC container: {0}", e);
throw;
}
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
container.RegisterWebApiFilterProvider(config);
try
{
new TraceListenersInitializer(container.GetInstance<IPortalMiddleendSettings>(), container.GetInstance<IEmailSenderService>()).Initialize();
}
catch (Exception e)
{
Trace.TraceError("Failed to initialize trace listeners: {0}", e);
throw;
}
}
示例2: SomeChooserBroken
public void SomeChooserBroken()
{
var choices = new List<char>()
{
'c',
'b',
'e',
'a',
'd'
};
var container = new Container();
var runner = container.GetInstance<RunnerBuilder>();
var fitness = container.GetInstance<FitnessScorer>();
var shadowRunners = runner.Create(choices).ToArray();
var descs = new List<string>();
for (int i = 0; i < shadowRunners.Length; i++)
{
var r = shadowRunners[i];
r.Score = fitness.CalculateScore(r);
descs.Add(r.ToString());
}
var count = descs.Count;
}
示例3: OnStart
public override bool OnStart()
{
var container = new Container();
try
{
// Building IoC container
Initialize(container);
container.Verify();
// Initializers
var initializers = new List<IInitializable>
{
container.GetInstance<TraceListenersInitializer>(),
container.GetInstance<DiagnosticsInitializer>()
};
foreach (IInitializable initializer in initializers)
{
initializer.Initialize();
}
}
catch (Exception e)
{
Trace.TraceError("Failed to start BillingSync worker role: {0}", e);
throw;
}
_container = container;
return base.OnStart();
}
示例4: Initialize
/// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
try
{
container.Verify();
}
catch (Exception exception)
{
Trace.TraceError("{0}", exception);
throw;
}
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.Services.Replace(typeof (IFilterProvider), new SimpleInjectorWebApiFilterProvider(container));
try
{
new TraceListenersInitializer(container.GetInstance<IPortalSettings>(), container.GetInstance<IEmailSenderService>()).Initialize();
}
catch (Exception e)
{
Trace.TraceError("Failed to initialize trace listeners: {0}", e);
throw;
}
}
示例5: RegisterServices
public void RegisterServices(Container container)
{
container.RegisterSingleton<IConfiguration, EnvironmentAwareAppSettingsConfiguration>();
container.RegisterSingleton(() =>
{
var config = container.GetInstance<IConfiguration>();
var useRedis = config.Get("UseRedis");
IDataServiceFactory factory;
if (bool.Parse(useRedis))
{
factory = new RedisDataServiceFactory(config);
}
else
{
factory = new DirectDataServiceFactory();
}
return factory;
});
container.RegisterSingleton(() => container.GetInstance<IDataServiceFactory>().Create());
container.RegisterSingleton<IAppSettings, AppSettings>();
}
示例6: ConfigureAspNetIdentity
private static void ConfigureAspNetIdentity(Container container)
{
container.Register(
typeof(IUserStore<Administrator>),
() =>
{
var session = container.GetInstance<IAsyncDocumentSession>();
session.Advanced.UseOptimisticConcurrency = true;
return new RavenUserStore<Administrator, RavenRole>(session);
},
Lifestyle.Scoped);
container.Register(
typeof(UserManager<Administrator>),
() =>
{
var manager = new UserManager<Administrator>(container.GetInstance<IUserStore<Administrator>>());
manager.UserValidator = new UserValidator<Administrator>(manager)
{
AllowOnlyAlphanumericUserNames = false,
};
return manager;
},
Lifestyle.Scoped);
}
示例7: Main
static void Main(string[] args)
{
var container = new Container();
RegisterInfrastructure(container);
var assemblies = GetAssemblies().ToArray();
container.RegisterSingleton<IMediator, Mediator>();
container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
container.Verify();
var mediator = container.GetInstance<IMediator>();
var commandsDbContext = container.GetInstance<ICommandsDbContext>();
Console.Write("creating users...");
Task.WaitAll(CreateUsersAsync(commandsDbContext, mediator));
Console.WriteLine("done!");
Console.Write("creating areas...");
Task.WaitAll(CreateAreasAsync(commandsDbContext, mediator));
Console.WriteLine("done!");
Console.Write("creating ideas...");
Task.WaitAll(CreateIdeasAsync(commandsDbContext, mediator));
Console.WriteLine("done!");
Console.Write("creating idea comments...");
Task.WaitAll(CreateIdeaCommentsAsync(commandsDbContext, mediator));
Console.WriteLine("done!");
Console.WriteLine("Feeding complete!");
Console.ReadLine();
}
示例8: Main
static void Main(string[] args)
{
//create the IOC container
var container = new Container();
//bind all our types to the interfaces
container.Register<IContactCreator, ContactCreator>();
container.Register<IContactLister, ContactLister>();
container.Register<IContactStore, MemoryContactStore>();
container.Register<ILog, NoLogging>();
var creator = container.GetInstance<IContactCreator>();
creator.Create(new Contact()
{
Name = "Guy"
});
creator.Create(new Contact()
{
Name = "Ascension"
});
creator.Create(new Contact()
{
Name = "Richard"
});
var lister = container.GetInstance<IContactLister>();
var contacts = lister.GetList();
foreach (var contact in contacts)
{
Console.WriteLine(contact.Name);
}
Console.ReadKey();
}
示例9: Index
public ActionResult Index()
{
Container container = new Container();
string apiKey = System.Configuration.ConfigurationManager.AppSettings["LeagueApiKey"];
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Singleton);
container.Register<IJsonRequestService, JsonRequestService>();
container.Register<ILeagueApiService>(() => new LeagueApiService(container.GetInstance<IJsonRequestService>(), apiKey));
container.Register<IChampionRepository, ChampionRepository>();
container.Register<IItemRepository, ItemRepository>();
container.Register<IDtoMapper<Champion, ChampionDTO>, ChampionDTOMapper>();
container.Register<IDtoMapper<Item, ItemDTO>, ItemDTOMapper>();
container.Register<UpdateDatabaseFromApiService>();
container.Register<LeagueItemsContext>(Lifestyle.Singleton);
container.Register<BuildGenerationService>();
container.Register<IBuildGenerationStrategy, HeuristicBuildGenerationStrategy>();
container.Verify();
BuildGenerationService buildGenerationService = container.GetInstance<BuildGenerationService>();
IUnitOfWork unitOfWork = container.GetInstance<IUnitOfWork>();
Champion jinx = unitOfWork.ChampionRepository.Get(106);
List<Item> buildItems = buildGenerationService.GetItemsForBuild(jinx.Builds.First());
return View(buildItems);
}
示例10: Application_Start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// Allow Any Certificates
// This should not be the same in Production
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
// Create the container as usual.
var container = new Container();
container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();
container.Register<IErrorSignaler, ErrorSignaler>(Lifestyle.Singleton);
container.Register<IHttpClientHelper, HttpClientHelper>(Lifestyle.Singleton);
container.Register<IConfigurationHelper, ConfigurationHelper>(Lifestyle.Singleton);
// SI Attributes Dependency Injection
container.RegisterInitializer<BlogApiAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());
container.RegisterInitializer<BlogAuthorizationAttribute>(a => a.ErrorSignaler = container.GetInstance<ErrorSignaler>());
// This is an extension method from the integration package.
container.RegisterMvcControllers(System.Reflection.Assembly.GetExecutingAssembly());
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(new SimpleInjector.Integration.Web.Mvc.SimpleInjectorDependencyResolver(container));
}
示例11: RegisterServices
// todo: only starting up subscriptions from web client for simplicity, should be done in console app (separate process)
public void RegisterServices(Container container) {
container.RegisterSingleton<ResolvedEventPublisher>();
container.Register<SubscriptionClient[]>(() => {
// todo: json configuration for subscription clients
string streamName = "$ce-user";
string groupName = "user-publisher";
PersistentSubscriptionSettingsBuilder settings = PersistentSubscriptionSettings.Create()
.ResolveLinkTos()
.StartFrom(0)
.MinimumCheckPointCountOf(1)
.MaximumCheckPointCountOf(1)
;
try {
IEventStoreConnection connection = container.GetInstance<Connection.IProvideConnection>().GetConnectionAsync().Result;
// todo: should not be creating the persistent subscription from code http://docs.geteventstore.com/dotnet-api/3.3.1/competing-consumers/
connection.CreatePersistentSubscriptionAsync(streamName, groupName, settings, new UserCredentials("admin", "changeit")).Wait();
} catch (AggregateException ex) when (ex.InnerException.Message.Equals($"Subscription group {groupName} on stream {streamName} already exists")) {
// subscription already exists
}
var userClients = new List<SubscriptionClient>();
Parallel.ForEach(Enumerable.Range(0, 9), x => {
userClients.Add(new SubscriptionClient(streamName, groupName,
container.GetInstance<Connection.IProvideConnection>(), container.GetInstance<ResolvedEventPublisher>()));
});
return userClients.ToArray();
}, Lifestyle.Singleton);
}
示例12: RunApp
private static void RunApp(Container container)
{
try
{
XamlGeneratedNamespace.GeneratedApplication app = new XamlGeneratedNamespace.GeneratedApplication();
((WpfApplication)container.GetInstance<IApplication>()).Initialize();
app.InitializeComponent();
app.Startup += (sender, args) =>
{
ThemeManager.AddAccent("WhiteAccent",
new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteAccent.xaml"));
ThemeManager.AddAppTheme("WhiteTheme",
new Uri("pack://application:,,,/DSImager.Application;component/Themes/WhiteTheme.xaml"));
};
var mainWin = container.GetInstance<MainWindow>();
container.GetInstance<ILogService>().Trace(LogEventCategory.Informational, "App is starting");
app.Run(mainWin);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
示例13: RegisterServices
public void RegisterServices(Container container) {
container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));
if (Settings.Current.EnableAppStats)
container.RegisterSingle<IAppStatsClient>(() => new AppStatsClient(Settings.Current.AppStatsServerName, Settings.Current.AppStatsServerPort));
else
container.RegisterSingle<IAppStatsClient, NullAppStatsClient>();
if (Settings.Current.RedisConnectionInfo == null)
throw new ConfigurationErrorsException("RedisConnectionString was not found in the Web.config.");
container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));
container.RegisterSingle<IRedisClientsManager>(() => new PooledRedisClientManager(Settings.Current.RedisConnectionInfo.ToString()));
container.Register<ICacheClient>(() => container.GetInstance<IRedisClientsManager>().GetCacheClient());
container.RegisterSingle<MongoDatabase>(() => {
if (String.IsNullOrEmpty(Settings.Current.MongoConnectionString))
throw new ConfigurationErrorsException("MongoConnectionString was not found in the Web.config.");
MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);
var url = new MongoUrl(Settings.Current.MongoConnectionString);
string databaseName = url.DatabaseName;
if (Settings.Current.AppendMachineNameToDatabase)
databaseName += String.Concat("-", Environment.MachineName.ToLower());
MongoServer server = new MongoClient(url).GetServer();
return server.GetDatabase(databaseName);
});
container.Register<ErrorStatsHelper>();
container.RegisterSingle<IErrorStackRepository, ErrorStackRepository>();
container.RegisterSingle<IErrorRepository, ErrorRepository>();
container.RegisterSingle<IOrganizationRepository, OrganizationRepository>();
container.RegisterSingle<IJobLockInfoRepository, JobLockRepository>();
container.RegisterSingle<IJobHistoryRepository, JobHistoryRepository>();
container.RegisterSingle<IProjectRepository, ProjectRepository>();
container.RegisterSingle<IUserRepository, UserRepository>();
container.RegisterSingle<IProjectHookRepository, ProjectHookRepository>();
container.RegisterSingle<MongoCollection<User>>(() => container.GetInstance<UserRepository>().Collection);
container.RegisterSingle<IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates"));
container.RegisterSingle<IMailer, Mailer>();
container.RegisterSingle<IMessageService, ExceptionlessMqServer>();
container.Register<IMessageFactory>(() => container.GetInstance<IMessageService>().MessageFactory);
container.Register<IDependencyResolver, SimpleInjectorCoreDependencyResolver>();
container.Register<MongoJobHistoryProvider>();
container.Register<MongoJobLockProvider>();
container.Register<MongoMachineJobLockProvider>();
container.Register<StartMqJob>();
container.Register<ErrorSignatureFactory>();
container.Register<StripeEventHandler>();
container.RegisterSingle<BillingManager>();
container.RegisterSingle<DataHelper>();
}
示例14: HumanStrategy
public HumanStrategy(Container container)
{
var randomCodeGenerator = container.GetInstance<IRandomCodeGenerator>();
_verifier = container.GetInstance<IVerifier>();
_guessHistory = new Queue<VerificationResult>();
_randomCode = randomCodeGenerator.Generate();
}
示例15: AllBrowsers
private static IEnumerable<IWebDriver> AllBrowsers(Container container)
{
if (container.GetRegistration(typeof(ChromeDriver)) != null)
yield return container.GetInstance<ChromeDriver>();
if (container.GetRegistration(typeof(InternetExplorerDriver)) != null)
yield return container.GetInstance<InternetExplorerDriver>();
if (container.GetRegistration(typeof(FirefoxDriver)) != null)
yield return container.GetInstance<FirefoxDriver>();
}