/// <summary> /// Executes the start action /// </summary> /// <param name="host"></param> /// <returns></returns> public new bool OnStart([CanBeNull] HostControl host) { base.Start(host); Host = host; const double interval = 60000; _timer = new Timer(interval); _timer.Elapsed += OnTick; _timer.AutoReset = true; _timer.Start(); Subscribe(); using (var scope = _container?.BeginLifetimeScope()) { var logger = scope?.Resolve <MSBaseLogger>(); logger?.LogInformation(Name + " Microservice Starting"); Console.WriteLine(Name + " Microservice Starting", Color.Yellow); } BitcoinSpendMessage m = new BitcoinSpendMessage(); m.amount = .50M; Bus.Publish(m, "Bitcoin.Spend"); return(true); }
private void InitializeWindow() { using (var scope = container.BeginLifetimeScope()) { ISpectrumFactory spectrumFactory = scope.Resolve <ISpectrumFactory>(); Results = scope.Resolve <IResults>(); spectrumFactory.Init(SearchParameters.Access.MSMSFile); StartScan = spectrumFactory.GetFirstScan(); EndScan = spectrumFactory.GetLastScan(); } }
static async Task Main(string[] args) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args); Configuration = builder.Build(); var conBuilder = new ContainerBuilder(); conBuilder.RegisterModule(new ContainerModule(Configuration)); ApplicationContainer = conBuilder.Build(); var scope = ApplicationContainer.BeginLifetimeScope(); var plugin = scope.Resolve <IStartService>(); await plugin.RunStatusUpdate(); await plugin.RunMailSend(); }
public async Task MainAsync() { ///////////initialize autofac autoFacContainer = AutofacConfig.ConfigureContainer(); using (var scope = autoFacContainer.BeginLifetimeScope()) { applicationSettings = scope.Resolve <ApplicationSettings>(); commands = scope.Resolve <CommandService>(); client = scope.Resolve <DiscordSocketClient>(); Logo(); //prints application name,version etc var appSettings = applicationSettings.Get(); //client = new DiscordSocketClient(); //_config = BuildConfig(); //commands = new CommandService(); //services = new ServiceCollection().BuildServiceProvider(); await InstallCommands(); await client.LoginAsync(TokenType.Bot, appSettings.DiscordSettings.Token); await client.StartAsync(); //client.UserJoined += UserJoined; } //client.MessageReceived += MessageReceived; await Task.Delay(-1); }
public static T Resolve <T>() { using (var scope = container.BeginLifetimeScope()) { return(scope.Resolve <T>()); } }
//ILogger logger; static void Main(string[] args) { LoadArgs(args); if (_loadHelp) { Console.WriteLine("Valid Parameters are /IsInteractive=[0|1] and /help"); return; } Autofac.IContainer container = BuildContainer(); ConfigureServices(container); using (var scope = container.BeginLifetimeScope()) { var pService = scope.Resolve <IProjectService>(); pService.DoProjectWork(); } if (_isInteractive) { Console.WriteLine("Done writing configured Documentation. Hit enter to continue."); Console.ReadLine(); } }
private void btnSave_Click(object sender, EventArgs e) { DialogResult = DialogResult.None; if (string.IsNullOrWhiteSpace(txtDescription.Text)) { MessageBoxHelper.ShowWarningMessage("Описание не может быть пустым", this); } using (var scope = _container.BeginLifetimeScope()) { var service = scope.Resolve <IDiscountDescriptionService>(); service.AddDescription(txtDescription.Text); } LoadItems(); }
IDependencyModule CreateInstance(Type moduleType) { using var innerScope = _optionsContainer.BeginLifetimeScope(b => b.RegisterType(moduleType).ExternallyOwned()); var module = (IDependencyModule)innerScope.Resolve(moduleType); _registeredModules[moduleType] = module; return(module); }
public void NormalExecutionReturnsExpectedObjects() { var settings = new ShellSettings { Name = ShellSettings.DefaultName }; var descriptor = new ShellDescriptor { SerialNumber = 6655321 }; var blueprint = new ShellBlueprint(); var shellLifetimeScope = _container.BeginLifetimeScope("shell"); var httpContext = new StubHttpContext(); _container.Mock <IShellDescriptorCache>() .Setup(x => x.Fetch(ShellSettings.DefaultName)) .Returns(descriptor); _container.Mock <ICompositionStrategy>() .Setup(x => x.Compose(settings, descriptor)) .Returns(blueprint); _container.Mock <IShellContainerFactory>() .Setup(x => x.CreateContainer(settings, blueprint)) .Returns(shellLifetimeScope); _container.Mock <IShellDescriptorManager>() .Setup(x => x.GetShellDescriptor()) .Returns(descriptor); _container.Mock <IWorkContextEvents>() .Setup(x => x.Started()); _container.Mock <IHttpContextAccessor>() .Setup(x => x.Current()) .Returns(default(HttpContextBase)); var factory = _container.Resolve <IShellContextFactory>(); var context = factory.CreateShellContext(settings); Assert.Same(context.Settings, settings); Assert.Same(context.Descriptor, descriptor); Assert.Same(context.Blueprint, blueprint); Assert.Same(context.LifetimeScope, shellLifetimeScope); //TODO why is same Assert.Same(context.Shell, shellLifetimeScope.Resolve <ISystemShell>()); }
/// <summary> /// Perform any desired configuration on container services /// </summary> /// <param name="container">The application container to be configured</param> static void ConfigureServices(Autofac.IContainer container) { using (var scope = container.BeginLifetimeScope()) { //Add NLog as a log consumer ILoggerFactory loggerFactory = scope.Resolve <ILoggerFactory>(); loggerFactory.AddNLog(); //notice: the project's only line of code referencing NLog (aside from .config) } }
private void AutoFacBenchmark(IContainer container) { using (container.BeginLifetimeScope()) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Continuing with AutoFac tests"); Stopwatch timer; TimeSpan elapsed5; timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass>(); } timer.Stop(); elapsed5 = timer.Elapsed; Singleton = new KeyValuePair <TimeSpan, TimeSpan>(Singleton.Key, elapsed5); Console.WriteLine("{0} instances created with singleton resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass2>(); } timer.Stop(); elapsed5 = timer.Elapsed; Transient = new KeyValuePair <TimeSpan, TimeSpan>(Transient.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.ResolveNamed <ITestClass>(ServiceName); } timer.Stop(); elapsed5 = timer.Elapsed; Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve <ITestClass3>(); if (instance.TClass == null) { Console.WriteLine("Injection failed"); } } timer.Stop(); elapsed5 = timer.Elapsed; TransientWithInjection = new KeyValuePair <TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds); } }
static void ConfigureServices(Autofac.IContainer container) { using (var scope = container.BeginLifetimeScope()) { //Add NLog as a log consumer ILoggerFactory loggerFactory = scope.Resolve <ILoggerFactory>(); loggerFactory.AddNLog(); loggerFactory.ConfigureNLog("nlog.config"); } }
private void metroButton1_Click(object sender, EventArgs e) { DialogResult = DialogResult.None; try { var check = Convert.ToDecimal(txtDiscountPercent.Text); } catch (FormatException) { MessageBoxHelper.ShowWarningMessage("Допустимы только цифры", this); return; } var number = Convert.ToDecimal(txtDiscountPercent.Text, CultureInfo.InvariantCulture); if (number == 0 || number <= -1) { MessageBoxHelper.ShowWarningMessage("Значение должно быть больше нуля", this); return; } if (txtDiscountPercent.Text.Length > 3 || number > 100) { MessageBoxHelper.ShowWarningMessage("Значение не может быть больше 100", this); return; } if (string.IsNullOrWhiteSpace(txtDiscountPercent.Text)) { MessageBoxHelper.ShowWarningMessage("Заполните поле", this); return; } using (var scope = _container.BeginLifetimeScope()) { var percentService = scope.Resolve <IDiscountPercentService>(); percentService.AddDiscountPercent(txtDiscountPercent.Text); } LoadItems(); }
private void AutoFacBenchmark(IContainer container) { using (container.BeginLifetimeScope()) { Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Continuing with AutoFac tests"); Stopwatch timer; TimeSpan elapsed5; timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass>(); } timer.Stop(); elapsed5 = timer.Elapsed; Singleton = new KeyValuePair<TimeSpan, TimeSpan>(Singleton.Key, elapsed5); Console.WriteLine("{0} instances created with singleton resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass2>(); } timer.Stop(); elapsed5 = timer.Elapsed; Transient = new KeyValuePair<TimeSpan, TimeSpan>(Transient.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves in {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.ResolveNamed<ITestClass>(ServiceName); } timer.Stop(); elapsed5 = timer.Elapsed; Console.WriteLine("{0} instances created with transient resolves by name {1} ms", Iterations, elapsed5.TotalMilliseconds); timer = Stopwatch.StartNew(); for (int i = 0; i < Iterations; i++) { var instance = container.Resolve<ITestClass3>(); if (instance.TClass == null) Console.WriteLine("Injection failed"); } timer.Stop(); elapsed5 = timer.Elapsed; TransientWithInjection = new KeyValuePair<TimeSpan, TimeSpan>(TransientWithInjection.Key, elapsed5); Console.WriteLine("{0} instances created with transient resolves with injection in {1} ms", Iterations, elapsed5.TotalMilliseconds); } }
/// <summary> /// 消费操作日志消息 /// </summary> private void ConsumerOperateLogMessage() { try { LogHelper.Info(() => "开始消费操作日志消息!"); ILogsOperateLogService _operateLogService; using (var scope = container.BeginLifetimeScope()) { _operateLogService = scope.Resolve <ILogsOperateLogService>(); } //使用发布/订阅模式消费消息 rabbitMQProxy.Subscribe <AddOperateLogRequest>(item => { _operateLogService.AddOperateLog(item); }); } catch (Exception ex) { LogHelper.Error(() => string.Format("消费操作日志消息时发生异常,详细信息:", ex.ToString())); } }
/// <summary> /// Process the given cancellationToken /// </summary> /// <param name="cancellationToken">The cancellation token</param> protected override void Process(CancellationToken cancellationToken) { Name = "Microservice Manager_" + Environment.MachineName; Start(); Subscribe(); using (var scope = _container?.BeginLifetimeScope()) { var logger = scope?.Resolve <MSBaseLogger>(); logger?.LogInformation(Name + " Microservice Starting"); Console.WriteLine(Name + " Microservice Starting", Color.Yellow); } const double interval = 60000; _timer = new Timer(interval); _timer.Elapsed += OnTick; _timer.AutoReset = true; _timer.Start(); RunRecoveringWatcher(); }
public static object[] TypesResolve(params Type[] types) { var resolvedTypes = new List <object>(); using (var scope = _container.BeginLifetimeScope()) { foreach (var type in types) { resolvedTypes.Add(scope.Resolve(type)); } } return(resolvedTypes.ToArray()); }
public static void Register(ContainerBuilder containerBuilder) { RegisterDatabase(containerBuilder); containerBuilder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); RegisterIdentity(containerBuilder); RegisterRepositories(containerBuilder); RegisterServices(containerBuilder); RegisterMaps(containerBuilder); RegisterControllers(containerBuilder); Container = containerBuilder.Build(); SetResolvers(); Container.BeginLifetimeScope(); }
public static List <Type> GenerateCommandTypes(AContainer container) { var commandClasses = new List <Type>(); using (var scope = container.BeginLifetimeScope()) { var types = scope.ComponentRegistry.Registrations .Where(r => typeof(ScriptCommand).IsAssignableFrom(r.Activator.LimitType)) .Select(r => r.Activator.LimitType).ToList(); commandClasses.AddRange(types); } return(commandClasses); }
public new bool OnStart([CanBeNull] HostControl host) { Host = host; Name = "Microservice Manager_" + Environment.MachineName; Start(host); Subscribe(); using (var scope = _container?.BeginLifetimeScope()) { var logger = scope?.Resolve <MSBaseLogger>(); logger?.LogInformation(Name + " Microservice Starting"); } Cache = CacheFactory.Build("MicroServiceCache", settings => settings.WithSystemRuntimeCacheHandle("MicroServiceCache")); const double interval = 60000; _timer = new Timer(interval); _timer.Elapsed += OnTick; _timer.AutoReset = true; _timer.Start(); return(true); }
private static void InitServiceLocator() { if (_autofacServiceLocator == null) { ContainerBuilder containerBuilder = new ContainerBuilder(); InitContainer(containerBuilder); _container = containerBuilder.Build(); } Messenger.Reset(); _currentScope = _container.BeginLifetimeScope(); _autofacServiceLocator = new AutofacServiceLocator(_currentScope); _isServiceLocatorSet = true; ServiceLocator.SetLocatorProvider(() => _autofacServiceLocator); }
/// <summary> /// 重新初始化自定义服务 /// </summary> private void ReservicesInit() { //string path = Application.StartupPath; //var dfd = GetServicePathBinding(path); //SetServicePathBinding(path, "Services/ServiceForPRARE;Services/ServiceForEasySocketService"); ContainerBuilder builder = new ContainerBuilder(); List <string> serviceNames = new List <string>(); Type baseType = typeof(IDependency); // 获取所有相关类库的程序集 Assembly[] assemblies = GetApiAssemblies(); List <NamedParameter> ListNamedParameter = new List <NamedParameter>() { new NamedParameter("opcClient", client) }; foreach (Assembly assembly in assemblies) { IEnumerable <Type> types = assembly.GetTypes() .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract); serviceNames.AddRange(types.Select(type => type.Name)); foreach (Type type in types) { builder.RegisterType(type) .Named <ITagService>(type.Name) .WithParameters(ListNamedParameter) .SingleInstance(); } } //构建容器来完成注册并准备对象解析。 Autofac.IContainer container = builder.Build(); // 现在您可以使用Autofac解决服务问题。例如,这一行将执行注册到IConfigReader服务的lambda表达式。 using (var scope = container.BeginLifetimeScope()) { tagServices.Clear(); foreach (var serviceName in serviceNames) { ITagService tagService = container.ResolveNamed <ITagService>(serviceName); tagService.MsgHandle = AddMsgToList; //tagService.Connect(); tagServices.Add(serviceName, tagService); AddMsgToList(serviceName + " > " + "[Loaded]"); } } }
static void Main(string[] args) { //Set up DI Autofac.IContainer _container = BuildContainer(); ConfigureServices(_container); //Accomplish something using our example service which depends on an external library //Resolve the service with dependencies injected - e.g. loggers using (var scope = _container.BeginLifetimeScope()) { IExampleService service = scope.Resolve <IExampleService>(); service.DoSomethingAsync().GetAwaiter().GetResult(); } //Wait to exit Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public static Type GetTypeByName(AContainer container, string typeName) { using (var scope = container.BeginLifetimeScope()) { var types = scope.ComponentRegistry.Registrations .Where(r => typeof(ScriptCommand).IsAssignableFrom(r.Activator.LimitType)) .Select(r => r.Activator.LimitType).ToList(); var commandType = types.Where(x => x.Name == typeName).FirstOrDefault(); if (commandType == null) { var packageName = GetPackageName(typeName); ShowErrorDialog($"Missing {packageName}, please download the package from Package Manager and retry."); } return(commandType); } }
public async Task MainAsync() { ///////////initialize autofac SettingsTripleZeroBot settingsTripleZeroBot = null; autoFacContainer = AutofacConfig.ConfigureContainer(); using (var scope = autoFacContainer.BeginLifetimeScope()) { applicationSettings = scope.Resolve <ApplicationSettings>(); commands = scope.Resolve <CommandService>(); client = scope.Resolve <DiscordSocketClient>(); logo = scope.Resolve <Logo>(); //memoryCache = scope.Resolve<MemoryCache>(); settingsTripleZeroBot = applicationSettings.GetTripleZeroBotSettings(); await InstallCommands(); await client.LoginAsync(TokenType.Bot, settingsTripleZeroBot.DiscordSettings.Token); await client.StartAsync(); await client.SetGameAsync(string.Format("{0}help", settingsTripleZeroBot.DiscordSettings.Prefix)); } //client.MessageReceived += MessageReceived; while (client.ConnectionState != ConnectionState.Connected) { Consoler.WriteLineInColor(string.Format("Still not connected... {0}", DateTime.Now), ConsoleColor.Yellow); await Task.Delay(2000); } logo.ConsolePrintLogo(); //prints application name,version etc //await TestCharAliasesDelete(); //await TestDelete(); //await TestGuildPlayers("41st"); //await TestPlayerReport("tsitas_66"); //await TestGuildModule("41s", "gk"); //await TestCharacterModule("tsitas_66", "cls"); await client.GetUser("TSiTaS", "1984").SendMessageAsync(logo.GetLogo()); await Task.Delay(-1); }
/// <summary> /// 初始化Opc服务 /// </summary> private IOpcClient OpcFinder(string opcName) { ContainerBuilder builder = new ContainerBuilder(); Type opcType = null; Type baseType = typeof(IOpcClient); // 获取所有OPC相关类库的程序集 Assembly[] assemblies = GetOpcAssemblies(); foreach (Assembly assembly in assemblies) { try { // opcType = assembly.GetTypes() //.Where(type => type.Name == opcName && baseType.IsAssignableFrom(type) && !type.IsAbstract).FirstOrDefault(); opcType = assembly.GetType(opcName); if (opcType != null) { builder.RegisterType(opcType) .Named <IOpcClient>(opcName) .SingleInstance(); break; } } catch (Exception ex) { AddMsgToList(ex.ToString()); } } //Autofac.IContainer container = builder.Build(); //IOpcClient opcClient = container.ResolveNamed<IOpcClient>(opcName); IOpcClient opcClient; //构建容器来完成注册并准备对象解析。 Autofac.IContainer container = builder.Build(); // 现在您可以使用Autofac解决服务问题。例如,这一行将执行注册到IConfigReader服务的lambda表达式。 using (var scope = container.BeginLifetimeScope()) { opcClient = container.ResolveNamed <IOpcClient>(opcName); } return(opcClient); }
// As soon as this page starts to be loaded it will navigate to my home page, passing all the neccessary stuff as it goes protected override async void OnAppearing() { if (!activityInd.IsRunning) { activityInd.IsRunning = true; // Checks local storage for users information var txtUsername = await Storage.ReadTextFileAsync(App.uNameLocation, DisplayError); var txtPwrd = await Storage.ReadTextFileAsync(App.pwrdLocation, DisplayError); // Checks if the app wants to use the custom api or RAWG Api // Is stored locally as a string of either true or false // Shorthand for multiple if statements checking if await Storage.ReadTextFileAsync(App.detailsLocation, _displayError) is equal to "true", if it is then it will return true, if not then it will return false App.useCustomAPI = await Storage.ReadTextFileAsync(App.customApiLocation, DisplayError) == "true" ? true : false; // If the username and password are not empty (Details are being remembered) then it will run this to log the user in if (!string.IsNullOrEmpty(txtUsername) && !string.IsNullOrEmpty(txtPwrd)) { container = DependancyInjection.Configure(); using (var scope = container.BeginLifetimeScope()) { var app = scope.Resolve <ILoginBackend>(); // If it runs into errors trying to log the user in then it'll display an alert, this is all handled automatically in my app using the DisplayError method which is a delegate var person = await app.GetUser(txtUsername, txtPwrd, DisplayError); if (person != null) { App.isLoggedIn = true; App.user = person; } } } // Navigates to another page and passes through click events and some methods like error handling await Navigation.PushAsync(new HomePage(LoginButton_Click, UserButton_Click, Search, DisplayError, GetGamesFromlist_Selected)); } }
public Form1() { //Init Autofac var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AsImplementedInterfaces(); //Force IXmlFeed to use mock //UseFakeXml(builder); UseRealXml(builder); container = builder.Build(); scope = container.BeginLifetimeScope(); InitializeComponent(); Form1Edit = this; fw = scope.Resolve <IFileWatcher>(); api = scope.Resolve <IXmlHelper>(); model = scope.Resolve <IMainModel>(); InstructionTextBox.Text = @"Instruction: The output csv file should be in the following format (Symbol,Profit,Win Ratio,Current Price)"; }
internal static ILifetimeScope BeginLifetimeScope() { return(_container.BeginLifetimeScope()); }
/// <summary> /// 作用域开始 /// </summary> public IScope BeginScope() { return(new Scope(_container.BeginLifetimeScope())); }
public static object Measure(IContainer container) { using (var scope = container.BeginLifetimeScope()) return(scope.Resolve <ScopedBlah>()); }