protected void Page_Load(object sender, EventArgs e) { IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container); if (Request["installation"] != null) { int installationid = Int32.Parse(Request["installation"]); userid = Int32.Parse(Request["userid"]); user = Request["user"]; sservice = container.Resolve<IStatisticService>(); IInstallationBL iinstall = container.Resolve<IInstallationBL>(); imodel = iinstall.getInstallation(installationid); Dictionary<InstallationModel, List<InstallationState>> statelist = sservice.getInstallationState(imodel.customerid); StringBuilder str = new StringBuilder(); str.Append("<table border = '1'><tr><th>Description</th><th>Messwert</th><th>Einheit</th></tr>"); foreach (var values in statelist) { if(values.Key.installationid.Equals(installationid)) { foreach (var item in values.Value) { str.Append("<tr><td>" + item.description + "</td><td>" + item.lastValue + "</td><td>" + item.unit + "</td></tr>"); } break; } } str.Append("</table>"); anlagenzustand.InnerHtml = str.ToString(); } }
public void WhenMultiWorkersAreConfiguredThenEndPointsNamesShouldHaveNumericalSuffixes() { var container = new UnityContainer(); new PollingHostRegistrar { SectionName = "phMultiWorkers" }.Register(container); Assert.AreEqual("Test_1", container.Resolve<PollProcessorEndpoint>("Test_1").Name); Assert.AreEqual("Test", container.Resolve<PollProcessorEndpoint>("Test").Name); }
public void Unity_registered_components_take_precedence_over_MEF_registered_components_if_querying_for_a_single_component_registered_in_both_containers() { // Setup var unityContainer = new UnityContainer(); var typeCatalog = new TypeCatalog(typeof (Singleton)); // Register catalog and types unityContainer.RegisterCatalog(typeCatalog); unityContainer.RegisterType<ISingleton, Singleton>(new ContainerControlledLifetimeManager()); // Reset count Singleton.Count = 0; Assert.That(Singleton.Count, Is.EqualTo(0)); var singleton = unityContainer.Resolve<ISingleton>(); Assert.That(singleton, Is.Not.Null); Assert.That(Singleton.Count, Is.EqualTo(1)); var mef = unityContainer.Resolve<CompositionContainer>(); var mefSingleton = mef.GetExportedValue<ISingleton>(); Assert.That(Singleton.Count, Is.EqualTo(1)); Assert.That(singleton, Is.SameAs(mefSingleton)); }
static void Main(string[] args) { int money; using (IUnityContainer container = new UnityContainer()) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container,"Employee"); Salary ms1 = container.Resolve<Salary>(); money = ms1.Calculate(80,100,1); Console.WriteLine("Unity =>" + money); section.Configure(container,"Boss"); ms1 = container.Resolve<Salary>(); money = ms1.Calculate(80,100,1); Console.WriteLine("Boss =>" + money); Console.ReadKey(); //test } }
private void UnityWithConfiguration() { // Create and populate a new Unity container from configuration UnityConfigurationSection UnityConfigurationSectionObject = (UnityConfigurationSection)ConfigurationManager.GetSection("UnityBlockConfiguration"); IUnityContainer UnityContainerObject = new UnityContainer(); UnityConfigurationSectionObject.Containers["ContainerOne"].Configure(UnityContainerObject); Console.WriteLine("\nRetrieved the populated Unity Container."); // Get the logger to write a message and display the result. No name in config file. ILogger ILoggerInstance = UnityContainerObject.Resolve < ILogger>(); Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO Default UNITY!")); // Resolve an instance of the appropriate class registered for ILogger // Using the specified mapping name in the configuration file (may be empty for the default mapping) ILoggerInstance = UnityContainerObject.Resolve<ILogger>("StandardLoggerMappedInConfig"); // Get the logger to write a message and display the result Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO StandardLogger!")); // Resolve an instance of the appropriate class registered for ILogger // Using the specified mapping name (may be empty for the default mapping) ILoggerInstance = UnityContainerObject.Resolve<ILogger>("SuperFastLoggerMappedInConfig"); // Get the logger to write a message and display the result Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO SuperFastLogger!")); // Constructor Injection. // Resolve an instance of the concrete MyObjectWithInjectedLogger class // This class contains a reference to ILogger in the constructor parameters MyObjectWithInjectedLogger MyObjectWithInjectedLoggerInstance = UnityContainerObject.Resolve<MyObjectWithInjectedLogger>(); // Get the injected logger to write a message and display the result Console.WriteLine("\n" + MyObjectWithInjectedLoggerInstance.GetObjectStringResult()); // Throws error as we are trying to create instance for interface. //IMyInterface IMyInterfaceObject = UnityContainerObject.Resolve<IMyInterface>(); IMyInterface IMyInterfaceObject = UnityContainerObject.Resolve<IMyInterface>(); Console.WriteLine("\n" + IMyInterfaceObject.GetObjectStringResult()); //If we are not sure whether a named registration exists for an object, // we can use the ResolveAll method to obtain a list of registrations and mappings, and then check for the object we need in the list returned by this method. // However, this will cause the container to generate all the objects for all named registrations for the specified object type, which will affect performance. IEnumerable<object> IEnumerableObjects = UnityContainerObject.ResolveAll(typeof(ILogger)); int i = 0; foreach (ILogger foundObject in IEnumerableObjects) { // Convert the object reference to the "real" type ILogger theObject = foundObject as ILogger; i++; if (null != theObject) { Console.WriteLine(theObject.WriteMessage("Reading Object " + i.ToString())); } } UnityContainerObject.Teardown(IMyInterfaceObject); Console.ReadLine(); }
static void Main(string[] args) { UnityContainer container = new UnityContainer(); container.RegisterType<IBankAccount, BankAccount>(); container.RegisterType<IBankAccountService, BankAccountService>(); container.RegisterType<IDeposit, Deposit>(); container.RegisterType<ITransfer, Transfer>(); container.RegisterType<IServiceFeeDeduction, ServiceFeeDeduction>(); Random rand = new Random(); var number = rand.Next(100000000, 999999999); BankAccount savings = new SavingsAccount() { AccountNumber = number, Balance = (decimal)8904.67, FreeTransactions = 21 }; ShowSavingsStatement(savings); Deposit dep = container.Resolve<Deposit>(); dep.DepositFunds(savings, (decimal)400.00); WriteYellowLine("Deposit was successful"); ShowSavingsStatement(savings); ServiceFeeDeduction fee = container.Resolve<ServiceFeeDeduction>(); fee.DeductServiceFee(savings); WriteYellowLine("Deduction was successful"); ShowSavingsStatement(savings); }
public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var container = new UnityContainer(); this.RegisterTypes(container); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); var settings = new JsonSerializerSettings(); settings.ContractResolver = new SignalRContractResolver(); var serializer = JsonSerializer.Create(settings); GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer); JsonConvert.DefaultSettings = () => new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; GlobalHost.DependencyResolver.Register(typeof(GameHub), () => new GameHub(container.Resolve<GameService>(), container.Resolve<ChatService>())); app.MapSignalR(new HubConfiguration { EnableDetailedErrors = true }); this.ConfigureOAuth(app); }
public ActionResult Login(string returnUrl) { // Users curUser = new Users(); // var dd = curUser.GetALL(); IUnityContainer container = new UnityContainer(); #region Ilogger // container.RegisterType<ILogger, ConsoleLogger>(); // ILogger logger = container.Resolve<ILogger>(); //string dd= logger.Log("Have a look!"); //container.RegisterType<ILogger, NullLogger>(); //ILogger logger2 = container.Resolve<ILogger>(); //string dd2 = logger2.Log("Have a look!"); #endregion container.RegisterType<IOrder, CommonOrder>(new ContainerControlledLifetimeManager()); IOrder order = container.Resolve<IOrder>(); order.Discount = 0.8; IOrder order2 = container.Resolve<IOrder>(); string dd = order2.DumpDiscount(); ViewBag.ReturnUrl = returnUrl; return View(); }
static void Main(string[] args) { IUnityContainer unityContainer = new UnityContainer(); IoCConvention.RegisterByConvention(unityContainer); var foobar = unityContainer.Resolve<IFooBar>(); Console.WriteLine(foobar.GetData()); var fooFactory = unityContainer.Resolve<IFooFactory>(); var foo1 = fooFactory.Create("1"); var foo2 = fooFactory.Create("2"); Console.WriteLine(foo1.GetData()); Console.WriteLine(foo2.GetData()); var fooCustomFactory = unityContainer.Resolve<IFooCustomFactory>(); var fooCustom1 = fooCustomFactory.Create("CustomName1"); var fooCustom2 = fooCustomFactory.Create("CustomName2"); Console.WriteLine(fooCustom1.GetData()); Console.WriteLine(fooCustom2.GetData()); var fooGenericString = unityContainer.Resolve<IFooGeneric<string>>(); Console.WriteLine(fooGenericString.GetData("dataType")); var fooGenericInt = unityContainer.Resolve<IFooGeneric<int>>(); Console.WriteLine(fooGenericInt.GetData(1)); Console.ReadLine(); }
partial void OnCreateContainer(UnityContainer container) { var serializer = container.Resolve<ITextSerializer>(); var metadata = container.Resolve<IMetadataProvider>(); var commandBus = new CommandBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Commands"), serializer); var eventBus = new EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer); var commandProcessor = new CommandProcessor(new MessageReceiver(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Commands"), serializer); var eventProcessor = new EventProcessor(new MessageReceiver(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer); container.RegisterInstance<ICommandBus>(commandBus); container.RegisterInstance<IEventBus>(eventBus); container.RegisterInstance<ICommandHandlerRegistry>(commandProcessor); container.RegisterInstance<IProcessor>("CommandProcessor", commandProcessor); container.RegisterInstance<IEventHandlerRegistry>(eventProcessor); container.RegisterInstance<IProcessor>("EventProcessor", eventProcessor); // Event log database and handler. container.RegisterType<SqlMessageLog>(new InjectionConstructor("MessageLog", serializer, metadata)); container.RegisterType<IEventHandler, SqlMessageLogHandler>("SqlMessageLogHandler"); container.RegisterType<ICommandHandler, SqlMessageLogHandler>("SqlMessageLogHandler"); RegisterRepository(container); RegisterEventHandlers(container, eventProcessor); }
public void MehrdeutigeKonstruktorenAufloesenTest() { var user = IoCContainer.Resolve <IUser>(); Assert.IsNotNull(user, "IUser sollte vom IoC auflösbar sein"); Assert.IsInstanceOfType(user, typeof(Mocks.User), "IUser sollte als Mocks.User aufgelöst werden"); }
public void Can_register_named_singleton_instance() { var container = new UnityContainer(); container.Configure(x => x.Register<IBarService, BarService>().WithName("name").AsSingleton()); Assert.That(container.Resolve<IBarService>("name"), Is.SameAs(container.Resolve<IBarService>("name"))); }
public void SetUp() { var container = new UnityContainer(); container.RegisterType<IDictionary<int, User>, Dictionary<int, User>>(new ContainerControlledLifetimeManager(), new InjectionConstructor()); _usersDictionary = container.Resolve<Dictionary<int, User>>(); container.RegisterType<IUserRepo, UserRepo>(new ContainerControlledLifetimeManager()); container.RegisterType<IFriendRepo, FriendRepo>(new ContainerControlledLifetimeManager()); container.RegisterType<IFriendNetworkRepo, FriendNetworkRepo>(new ContainerControlledLifetimeManager()); container.RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager(), new InjectionConstructor(_usersDictionary)); container.RegisterType<ServiceControllers.FriendsController, ServiceControllers.FriendsController>(); container.RegisterType<ServiceControllers.UsersController, ServiceControllers.UsersController>(); _unitOfWork = container.Resolve<IUnitOfWork>(); _mockUser = new MockUser(); _random = new Random(); _uniqueIdMock = new UniqueIdMock(0); for (var i = 1; i <= Total; i++) { add_new_user_test_dictionary("s" + i, i.ToString(CultureInfo.InvariantCulture)); } }
private static async Task<string> LargeBatchInsert() { IUnityContainer container = new UnityContainer(); UnityApplicationFrameworkDependencyResolver resolver = new UnityApplicationFrameworkDependencyResolver(container); resolver .UseCore(defaultTraceLoggerMinimumLogLevel: LogLevelEnum.Verbose) .UseAzure(); var resourceManager = container.Resolve<IAzureResourceManager>(); var tableStorageRepositoryFactory = container.Resolve<ITableStorageRepositoryFactory>(); var table = tableStorageRepositoryFactory.CreateAsynchronousNoSqlRepository<SampleEntity>(StorageAccountConnectionString, TableName); await resourceManager.CreateIfNotExistsAsync(table); string partitionKey = Guid.NewGuid().ToString(); List<SampleEntity> entities = new List<SampleEntity>(); for (int item = 0; item < 725; item++) { entities.Add(new SampleEntity { Name = $"Name {item}", PartitionKey = partitionKey, RowKey = Guid.NewGuid().ToString() }); } await table.InsertBatchAsync(entities); Console.WriteLine($"Inserted 725 items into partition {partitionKey}"); return partitionKey; }
partial void OnCreateContainer(UnityContainer container) { var metadata = container.Resolve<IMetadataProvider>(); var serializer = container.Resolve<ITextSerializer>(); // blob var blobStorageAccount = CloudStorageAccount.Parse(azureSettings.BlobStorage.ConnectionString); container.RegisterInstance<IBlobStorage>(new SqlBlobStorage("BlobStorage")); var commandBus = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path), metadata, serializer); var topicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path); container.RegisterInstance<IMessageSender>(topicSender); var eventBus = new EventBus(topicSender, metadata, serializer); var commandProcessor = new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, "all", false, new SubscriptionReceiverInstrumentation("all", this.instrumentationEnabled)), serializer); container.RegisterInstance<ICommandBus>(commandBus); container.RegisterInstance<IEventBus>(eventBus); container.RegisterInstance<IProcessor>("CommandProcessor", commandProcessor); RegisterRepository(container); RegisterEventProcessors(container); RegisterCommandHandlers(container, commandProcessor); }
private static async Task SimpleSaveAndRetrieve() { IUnityContainer container = new UnityContainer(); UnityApplicationFrameworkDependencyResolver resolver = new UnityApplicationFrameworkDependencyResolver(container); resolver .UseCore(defaultTraceLoggerMinimumLogLevel:LogLevelEnum.Verbose) .UseAzure(); var resourceManager = container.Resolve<IAzureResourceManager>(); var tableStorageRepositoryFactory = container.Resolve<ITableStorageRepositoryFactory>(); var table = tableStorageRepositoryFactory.CreateAsynchronousNoSqlRepository<SampleEntity>(StorageAccountConnectionString, TableName); await resourceManager.CreateIfNotExistsAsync(table); string partitionKey = Guid.NewGuid().ToString(); string rowKey = Guid.NewGuid().ToString(); await table.InsertAsync(new SampleEntity { Name = "Someone New", PartitionKey = partitionKey, RowKey = rowKey }); SampleEntity retrievedEntity = await table.GetAsync(partitionKey, rowKey); Console.WriteLine(retrievedEntity.Name); }
protected override void OnStartup(StartupEventArgs e) { IUnityContainer container = new UnityContainer(); container.AddNewExtension<LazySupportExtension>(); // Register grooveshark related stuff container.RegisterType<IGroovesharkClient, GroovesharkClientWrapper>( new ContainerControlledLifetimeManager(), new InjectionMethod("Connect")); container.RegisterType<ISongProvider, GroovesharkSongProvider>( GroovesharkSongProvider.ProviderName, new ContainerControlledLifetimeManager()); container.RegisterType<ISongPlayer, GroovesharkSongPlayer>( GroovesharkSongProvider.ProviderName, new ContainerControlledLifetimeManager()); // Register spotify/torshify related stuff container.RegisterType<ISongProvider, SpotifySongProvider>( SpotifySongProvider.ProviderName, new ContainerControlledLifetimeManager()); container.RegisterType<ISongPlayer, TorshifySongPlayerClient>( SpotifySongProvider.ProviderName, new ContainerControlledLifetimeManager()); container.RegisterType<ISpotifyImageProvider, TorshifyImageProvider>(); // Aggregate provider that combines Grooveshark and Spotify players and providers container.RegisterType<ISongProvider, AggregateSongProvider>(new InjectionFactory(c => { var a = new AggregateSongProvider( c.Resolve<ISongProvider>(GroovesharkSongProvider.ProviderName), c.Resolve<ISongProvider>(SpotifySongProvider.ProviderName)); a.UnhandledException += (sender, args) => { Trace.WriteLine(args.Exception); args.Handled = true; }; return a; })); container.RegisterType<ISongPlayer, AggregateSongPlayer>(new InjectionFactory(c => { return new AggregateSongPlayer( c.Resolve<ISongPlayer>(GroovesharkSongProvider.ProviderName), c.Resolve<ISongPlayer>(SpotifySongProvider.ProviderName)); })); TorshifyServerProcessHandler torshifyServerProcess = new TorshifyServerProcessHandler(); torshifyServerProcess.CloseServerTogetherWithClient = true; //torshifyServerProcess.Hidden = true; torshifyServerProcess.TorshifyServerLocation = Path.Combine(Environment.CurrentDirectory, "TRock.Music.Torshify.Server.exe"); torshifyServerProcess.UserName = "******"; torshifyServerProcess.Password = "******"; torshifyServerProcess.Start(); var provider = container.Resolve<ISongProvider>(); MainWindow = container.Resolve<MainWindow>(); MainWindow.Show(); }
private static void Main(string[] args) { var uc = new UnityContainer(); AddDependencies(uc); var api = uc.Resolve<IApi>(); var output = uc.Resolve<IOutputService>(); try { var message = api.Execute(args); output.WriteMessage(message); } catch (ArgumentNullException) { output.WriteMessage("Невалидный аргумент"); } catch (InvalidOperationException) { output.WriteMessage("Невозможно выполнить операцию"); } catch (InvalidCastException) { output.WriteMessage("Дата должна иметь формат дд.мм.гггг"); } Console.ReadKey(); }
public void Combined_Test() { var container = new UnityContainer(); container.AddNewExtension<DisposableStrategyExtension>(); container.RegisterType<DisposableClass>("transient", new DisposingTransientLifetimeManager()); container.RegisterType<DisposableClass>("shared", new DisposingSharedLifetimeManager()); var transient1 = container.Resolve<DisposableClass>("transient"); var transient2 = container.Resolve<DisposableClass>("transient"); Assert.AreNotEqual(transient1, transient2); var shared1 = container.Resolve<DisposableClass>("shared"); Assert.AreNotEqual(transient1, shared1); Assert.AreNotEqual(transient2, shared1); var shared2 = container.Resolve<DisposableClass>("shared"); Assert.AreEqual(shared1, shared2); container.Teardown(transient1); Assert.IsTrue(transient1.Disposed); container.Teardown(shared2); Assert.IsFalse(shared2.Disposed); container.Teardown(shared1); Assert.IsTrue(shared1.Disposed); }
public static void Main(string[] args) { var diContainer = new UnityContainer(); diContainer.LoadConfiguration(); var source = diContainer.Resolve<ISnapshotSource>(); while (true) { Console.WriteLine("Retrieving snapshots..."); var snapshots = source.GetSnapshots(); Parallel.ForEach(snapshots, snapshot => { var handler = diContainer.Resolve<ISnapshotSink>(); Console.WriteLine("Writing snapshot..."); handler.HandleSnapshot(snapshot); }); Console.WriteLine("Sleeping..."); Thread.Sleep(TimeSpan.FromSeconds(30)); } }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var container = new UnityContainer(); container.RegisterType<IUdpClientServer, UdpClientServer>(new ContainerControlledLifetimeManager()); var serverAddress = ConfigurationManager.AppSettings.Get("ServerAddress"); var serverPort = int.Parse(ConfigurationManager.AppSettings.Get("ServerPort")); container.RegisterInstance<IChannelConfig>(ChannelNames.Server, new ChannelConfig { Address = serverAddress, Port = serverPort }, new ContainerControlledLifetimeManager()); container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>( ChannelNames.Server, new ContainerControlledLifetimeManager(), new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Server)))); var clientAddress = ConfigurationManager.AppSettings.Get("ClientAddress"); var clientPort = int.Parse(ConfigurationManager.AppSettings.Get("ClientPort")); container.RegisterInstance<IChannelConfig>(ChannelNames.Client, new ChannelConfig { Address = clientAddress, Port = clientPort }, new ContainerControlledLifetimeManager()); container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>( ChannelNames.Client, new ContainerControlledLifetimeManager(), new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Client)))); container.RegisterType(typeof(IService<,>), typeof(Service<,>), new ContainerControlledLifetimeManager()); container.RegisterType(typeof(ITopic<>), typeof(Topic<>), new ContainerControlledLifetimeManager()); var ch = container.Resolve<ICommunicationChannel>(ChannelNames.Client); ch.SendMessage(new UserQuery("xxx")); container.RegisterType<MainWindowViewModel, MainWindowViewModel>(new ContainerControlledLifetimeManager()); container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager()); container.Resolve<MainWindow>().Show(); }
static DetailsViewHandler() { IUnityContainer uContainer = new UnityContainer(); _movieManagementService = uContainer.Resolve<MovieManagementService>(); _songManagementService = uContainer.Resolve<SongManagementService>(); _bookManagementService = uContainer.Resolve<BookManagementService>(); }
public void Test() { using (var container = new UnityContainer()) { container.RegisterType<ITestClass, TestClass>(); container.AddNewExtension<LazyExtension>(); var testClass1 = container.Resolve<Lazy<ITestClass>>(); Assert.AreEqual(false, testClass1.IsValueCreated); Assert.AreEqual(0, TestClass.InstanceCount); Assert.AreEqual(5, testClass1.Value.HighFive()); Assert.AreEqual(true, testClass1.IsValueCreated); Assert.AreEqual(1, TestClass.InstanceCount); var testClass2 = container.Resolve<Lazy<ITestClass>>(); Assert.AreEqual(false, testClass2.IsValueCreated); Assert.AreEqual(1, TestClass.InstanceCount); Assert.AreEqual(5, testClass2.Value.HighFive()); Assert.AreEqual(true, testClass2.IsValueCreated); Assert.AreEqual(2, TestClass.InstanceCount); } }
public void InjectClassWithTwoConstructors() { int myInt = 37; string myStr = "Test"; IUnityContainer container = new UnityContainer(); //constructor without params container.Configure<InjectedMembers>().ConfigureInjectionFor<TestClass>(new InjectionConstructor()); TestClass withOutCon = container.Resolve<TestClass>(); Assert.IsFalse(withOutCon.StringConstructorCalled); Assert.IsFalse(withOutCon.IntConstructorCalled); //constructor with one param container.Configure<InjectedMembers>() .ConfigureInjectionFor<TestClass>("First", new InjectionConstructor(myInt)); TestClass myTestClass = container.Resolve<TestClass>("First"); Assert.IsFalse(myTestClass.StringConstructorCalled); Assert.IsTrue(myTestClass.IntConstructorCalled); //constructor with one param container.Configure<InjectedMembers>() .ConfigureInjectionFor<TestClass>("Second", new InjectionConstructor(myStr)); TestClass myTestClass1 = container.Resolve<TestClass>("Second"); Assert.IsFalse(myTestClass1.IntConstructorCalled); Assert.IsTrue(myTestClass1.StringConstructorCalled); }
public void UnityCanAccessMixedMefAndUnityComponents() { var unityContainer = new UnityContainer(); // Register MEF catalog in Unity unityContainer.RegisterCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly())); unityContainer.RegisterType<IUnityService1, UnityService1>( new ContainerControlledLifetimeManager(), true); // Most complex test: UnityComponent2 has dependencies on both Unity // and MEF components while specified MEF component has further // dependencies on both Unity and MEF components var unityComponent2 = unityContainer.Resolve<UnityComponent2>(); Assert.IsNotNull(unityComponent2); var mefComponent3 = unityContainer.Resolve<IMefComponent1>("MefComponent3"); Assert.IsNotNull(mefComponent3); Assert.IsTrue(mefComponent3 is MefComponent3); var unityService1 = unityContainer.Resolve<IUnityService1>(); Assert.IsNotNull(unityService1); Assert.AreSame(mefComponent3, unityComponent2.MefComponent1); Assert.AreSame(unityService1, unityComponent2.UnityService1); Assert.IsTrue(unityComponent2.MefComponent1 is MefComponent3); var originalMefComponent3 = (MefComponent3)unityComponent2.MefComponent1; Assert.IsNotNull(originalMefComponent3.MefComponent1); Assert.IsNotNull(originalMefComponent3.UnityService1); }
public void Should_Only_Record_For_Types_Declared_In_Config_File() { var container = new UnityContainer().LoadConfiguration("BetamaxWithConfig"); Assert.That(container.Resolve<SimpleWidgetService>().GetType().FullName, Is.StringEnding("DummyWidgetService")); Assert.That(container.Resolve<WidgetService>().GetType().FullName, Is.StringEnding("Proxy")); }
private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); container.RegisterType<UDI.EF.DAL.IEFContext, UDI.EF.DAL.EFContext>(new ContainerControlledLifetimeManager()); container.Resolve<UDI.EF.DAL.IEFContext>(); //container.RegisterType(typeof(IRepository<>), typeof(EFGenericRepository<>)); //Bind the various domain model services and repositories that e.g. our controllers require //Register interfaces in CORE container.RegisterType(typeof(UDI.CORE.Repositories.IRepository<>), typeof(UDI.EF.Repositories.EFRepositoryBase<>)); container.RegisterType<UDI.CORE.Services.ICategoryService, UDI.CORE.Services.Impl.CategoryService>(); container.RegisterType<UDI.CORE.Services.ICustomerService, UDI.CORE.Services.Impl.CustomerService>(); container.RegisterType<UDI.CORE.Services.IOrderService, UDI.CORE.Services.Impl.OrderService>(); container.RegisterType<UDI.CORE.Services.IProductService, UDI.CORE.Services.Impl.ProductService>(); container.RegisterType<UDI.CORE.Services.IUserService, UDI.CORE.Services.Impl.UserService>(); container.RegisterType<UDI.CORE.UnitOfWork.IUnitOfWork, UDI.EF.UnitOfWork.EFUnitOfWork>(new ContainerControlledLifetimeManager()); container.Resolve<UDI.CORE.UnitOfWork.IUnitOfWork>(); container.RegisterType<UDI.CORE.UnitOfWork.IUnitOfWorkManager, UDI.EF.UnitOfWork.EFUnitOfWorkManager>(); //Register interfaces in EF container.RegisterType<UDI.EF.DAL.IEFContext, UDI.EF.DAL.EFContext>(); //return container; RegisterTypes(container); return container; }
public Game(IDrawer drawer, uint width, uint height) { curRect.Width = width; curRect.Height = height; Intervals = Observable.Interval(TimeSpan.FromMilliseconds(TimeStep)); _unityContainer = new UnityContainer(); this.RegisterInUnityContainer(); StateQueueManager = _unityContainer.Resolve<StateQueueManager>(); Map = _unityContainer.Resolve<Map>(); loadSaveManager = new LoadSaveManager(); loadSaveManager.LoadSnapshot(Map); _hero = _unityContainer.Resolve<Hero>(); _hero.Map = Map; ActionRepository = _unityContainer.Resolve<IActionRepository>(); _drawer = drawer; Intervals.Subscribe(StateQueueManager); _dayNightCycle = new DayNightCycle(); Intervals.Subscribe(_dayNightCycle); }
partial void OnCreateContainer(UnityContainer container) { var metadata = container.Resolve<IMetadataProvider>(); var serializer = container.Resolve<ITextSerializer>(); var commandBus = new CommandBus(new TopicSender(azureSettings.ServiceBus, Topics.Commands.Path), metadata, serializer); var topicSender = new TopicSender(azureSettings.ServiceBus, Topics.Events.Path); container.RegisterInstance<IMessageSender>(topicSender); var eventBus = new EventBus(topicSender, metadata, serializer); var commandProcessor = new CommandProcessor(new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.All), serializer); container.RegisterInstance<ICommandBus>(commandBus); container.RegisterInstance<IEventBus>(eventBus); container.RegisterInstance<ICommandHandlerRegistry>(commandProcessor); container.RegisterInstance<IProcessor>("CommandProcessor", commandProcessor); RegisterRepository(container); RegisterEventProcessors(container); // message log var messageLogAccount = CloudStorageAccount.Parse(azureSettings.MessageLog.ConnectionString); container.RegisterInstance<IProcessor>("EventLogger", new AzureMessageLogListener( new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName), new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Events.Path, Topics.Events.Subscriptions.Log))); container.RegisterInstance<IProcessor>("CommandLogger", new AzureMessageLogListener( new AzureMessageLogWriter(messageLogAccount, azureSettings.MessageLog.TableName), new SubscriptionReceiver(azureSettings.ServiceBus, Topics.Commands.Path, Topics.Commands.Subscriptions.Log))); }
public static void Run() { var container = new UnityContainer(); container.RegisterType<IConfiguration, LocalConfiguration>(new ContainerControlledLifetimeManager()); IConfiguration configuration = container.Resolve<IConfiguration>(); container.RegisterType<ILogger, EventLogLogger>(); container.RegisterType<IQueueAdapter, QueueAdapter>(); IQueueAdapter adapter = container.Resolve<IQueueAdapter>(); string msmqNonTransactionalPath1 = configuration["msmqNonTransactionalPath1"]; adapter.CreateQueue(msmqNonTransactionalPath1); while (!Console.KeyAvailable) { Console.WriteLine( string.Format( "{0}: {1}", msmqNonTransactionalPath1, adapter.SendMessage(msmqNonTransactionalPath1, new MentoringMessage()))); Thread.Sleep(1000); } }
public override bool OnStart() { // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. RoleEnvironment.Changing += RoleEnvironmentChanging; RoleEnvironment.Changed += RoleEnvironmentChanged; using (var container = new UnityContainer()) { ContainerBootstraper.RegisterTypes(container, true); container.Resolve<ISurveyStore>().Initialize(); container.Resolve<ISurveyAnswerStore>().Initialize(); container.Resolve<ISurveyAnswersSummaryStore>().Initialize(); container.Resolve<ISurveyTransferStore>().Initialize(); var tenantStore = container.Resolve<ITenantStore>(); tenantStore.Initialize(); // Set Adatum's logo SetLogo("adatum", tenantStore, TenantInitLogo.adatum_logo); // Set Fabrikam's logo SetLogo("fabrikam", tenantStore, TenantInitLogo.fabrikam_logo); return base.OnStart(); } }
public static void Initialize() { var container = new Microsoft.Practices.Unity.UnityContainer(); GlobalConfiguration.Configuration.DependencyResolver = new QMailer.UnityDependencyResolver(container); GlobalConfiguration.Configuration.FullUrl = "http://localhost"; GlobalConfiguration.Configuration.SenderEmail = "*****@*****.**"; GlobalConfiguration.Configuration.SenderName = "TestEmail"; var existingBus = container.Resolve <Ariane.IServiceBus>(); container.RegisterType <Ariane.IServiceBus, Ariane.SyncBusManager>(new ContainerControlledLifetimeManager(), new InjectionConstructor(existingBus)); var bus = container.Resolve <Ariane.IServiceBus>(); bus.Register.AddQueue(new QueueSetting() { AutoStartReading = true, Name = GlobalConfiguration.Configuration.EmailBodyRequestedQueueName, TypeMedium = typeof(Ariane.InMemoryMedium), TypeReader = typeof(QMailer.Web.EmailBodyRequestedMessageReader) }); bus.Register.AddQueue(new QueueSetting() { AutoStartReading = true, Name = GlobalConfiguration.Configuration.SendEmailQueueName, TypeMedium = typeof(Ariane.InMemoryMedium), TypeReader = typeof(QMailer.SendEmailMessageReader) }); QMailerService.ReplaceBusService(bus); QMailer.Web.QMailerConfig.Configure(container); var viewEngines = new Moq.Mock <ViewEngineCollection>(); var fakeView = new FakeView(); viewEngines.Setup(i => i.FindView(Moq.It.IsAny <ControllerContext>(), "test", null)) .Returns(new ViewEngineResult(fakeView, Moq.Mock.Of <IViewEngine>())); var fakeRenderer = new QMailer.Web.EmailViewRenderer(viewEngines.Object, "http://localhost", "~/emailviews"); container.RegisterInstance <QMailer.Web.IEmailViewRenderer>(fakeRenderer, new ContainerControlledLifetimeManager()); container.RegisterType <QMailer.ILogger, QMailer.DiagnosticsLogger>(new ContainerControlledLifetimeManager()); }
static void Main(string[] args) { string cpf = "05039162693"; CultureInfo ci = new CultureInfo("pt-BR"); Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; var container = new Microsoft.Practices.Unity.UnityContainer(); DependencyResolver.Resolve(container); var service = container.Resolve <IClientAppService>(); #region Salvar try { //List<Phone> listPhones = new List<Phone> //{ // new Phone {ClientId = 3, Number = "1111"}, // new Phone {ClientId = 3, Number = "2222"}, // new Phone {ClientId = 3, Number = "3333"} //}; //Client client = new Client(cpf, "Rua Nogueira de Paiva, 30 Casa 09", "Jean Tadeu Ferreira", "*****@*****.**", MaritalStatus.Single, null); //service.Register(client); } catch (Exception ex) { Console.WriteLine(ex.Message); } #endregion try { var clients = service.GetAll(); foreach (var c in clients) { Console.WriteLine(c.Name + "\t" + c.Address); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
public ValidateUser() { UnityContainer resolver = new Microsoft.Practices.Unity.UnityContainer(); _userServices = resolver.Resolve <UserServices>(); }