public void CachedLifetimeReturnsDifferentInstanceIfSlidingTimeoutHaveExpired() { using (var container = new IocContainer()) { // Expires When not Accessed For More than a specific time periode. var lifetime = new CachedLifetime(new TimeSpan(0, 0, 1)); container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime); var result1 = container.Resolve<IFoo>(); var result2 = container.Resolve<IFoo>(); // Simulate expiry Thread.Sleep(2000); var result3 = container.Resolve<IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
static void Main(string[] args) { var container = new IocContainer(); container.RegisterFromAssemblyOf<Program>(); Configure.Messaging() .LoggingWith(new ConsoleLoggingMechanism {ShowInfo = false, ShowDebug = false}) .ResolveReferencesWith(container) .RegisterHandlersFromContainer().BasedOn<IMessageConsumer>() .UsingHttpTransport() .AsAServer("OtherSenderServer") .OpenDirectChannel("OtherTestRequest") .ForRequestReplySendingTo("TestReply@ReceiverServer") .Initialise(); do { Console.WriteLine("I am the other sender. Press enter to send messages.."); Console.ReadLine(); Console.WriteLine("Sending messages"); Bus.SendDirect(new TestMessage("Hello")); Bus.SendDirect(new TestMessage("Hello1")); Bus.SendDirect(new TestMessage("Hello2")); Bus.SendDirect(new TestMessage("Hello3")); Bus.SendDirect(new TestMessage("Hello4")); Bus.SendDirect(new TestMessage("Hello5")); Bus.SendDirect(new TestMessage("Hello6")); Bus.SendDirect(new TestMessage("Hello7")); } while (true); }
/// <summary> /// Finds all the types that implement the IMunqConfig interface, create an instance and /// then call the RegisterIn method on the type. The bin directory is checked for web /// applications, the current directory for Windows applications. /// </summary> /// <param name="container">The Munq IOC container to register class factories in.</param> public static void FindAndRegisterDependencies(IocContainer container) { // get all the assemblies in the bin directory string binPath = HttpContext.Current != null ? HttpContext.Current.Server.MapPath("/bin") : Environment.CurrentDirectory; CallRegistrarsInDirectory(container, binPath); }
public void ContainerCanBeCreated() { using (var container = new IocContainer()) { Assert.IsNotNull(container); } }
public void ContainerScopeTryResolveWorks() { using (var container = new IocContainer()) { // Register container.Register<IFoo, Foo1>(); container.Register<IFoo, Foo2>("Key1"); container.Register<IBar, Bar1>(); using (var scope = container.GetScope()) { IFoo instance1, instance2; var result1 = scope.TryResolve<IFoo>(out instance1); var result2 = scope.TryResolve<IFoo>(out instance2); Assert.AreSame(instance1, instance2); IFooBar instance3, instance4; var result3 = scope.TryResolve<IFooBar>(out instance3); var result4 = scope.TryResolve<IFooBar>(out instance4); Assert.AreSame(instance3, instance4); } } }
/// <summary> /// Finds all the types that implement the IMunqConfig interface, create an instance and /// then call the RegisterIn method on the type. /// </summary> /// <param name="container">The Munq IOC container to register the class factories in.</param> /// <param name="binPath">The path of the directory to search.</param> /// <param name="filePattern">The optional file pattern for files to check. The default is *.dll</param> public static void CallRegistrarsInDirectory(IocContainer container, string binPath, string filePattern = "*.dll") { var assemblyNames = Directory.GetFiles(binPath, filePattern); foreach (var filename in assemblyNames) CallRegistrarsInAssembly(container, filename); }
public void CachedLifetimeReturnsDifferentInstanceIfCacheExpired() { using (var container = new IocContainer()) { var policy = new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, 0, 1) }; container.Register<IFoo>(c => new Foo1()).WithCachedLifetime(policy); var result1 = container.Resolve<IFoo>(); var result2 = container.Resolve<IFoo>(); Thread.Sleep(1500); var result3 = container.Resolve<IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { var ioc = new IocContainer(); CustomRegistrations(ioc); AutoRegistrations(ioc); var messages = new List<string> { ioc.Resolve<ISomething>().Say(), ioc.Resolve<Something>().Say(), ioc.Resolve<ISomethingOrOther>().Say(), ioc.Resolve<IInterfaceForBaseType>().Say(), ioc.Resolve<IInterfaceForDerivedType>().Say(), ioc.Resolve<ICustomInterface>().Say() }; try { ioc.Resolve<Object>(); } catch (TypeNotRegisteredException ex) { messages.Add(ex.Message); } var dialogContent = string.Empty; messages.ForEach(m => dialogContent += m + Environment.NewLine); await new MessageDialog(dialogContent).ShowAsync(); Application.Current.Exit(); }
static void Main(string[] args) { var container = new IocContainer(); container.RegisterFromAssemblyOf<Program>(); Configure.Messaging() .LoggingWith(new ConsoleLoggingMechanism { ShowDebug = false }) .UsingFilePersistence() .ResolveReferencesWith(container) .RegisterHandlersFromContainer().BasedOn<IMessageHandler>() .UsingHttpTransport() .AsAServer("ReceiverServer") .RequiresAuthentication() .AcceptsRequest<AuthenticationRequest>() .AuthenticatesOnReply<AuthenticatedResponse>() .ExpiresAfter(TimeSpan.FromMinutes(1)) .OnExpiry(s => Console.WriteLine("Session expired: {0}", s)) .OpenChannel("TestReply") .ForRequestReplyReceiving() .WithDurability() .Initialise(); Console.WriteLine("I am the reciever. Press enter to exit"); Console.ReadLine(); }
public void CachedLifetimeCanBeSetAsDefaultLifetime() { using (var container = new IocContainer(() => new CachedLifetime())) { Assert.IsInstanceOfType(container.DefaultLifetimeFactory(), typeof(CachedLifetime)); } }
public Broadcasters(XDMessagingClient messagingClient, IocContainer container) : base(container) { Validate.That(messagingClient).IsNotNull(); this.messagingClient = messagingClient; }
public ServiceBuilder(IocContainer container) { if(container == null) throw new ArgumentNullException(nameof(container)); this._container = container; this.TypeBinders = new Lazy<List<TypeServiceBinder>>(); this.ValueBinders = new Lazy<List<ValueServiceBinder>>(); }
static void Main(string[] args) { var container = new IocContainer(); container.RegisterFromAssemblyOf<Program>(); Configure.Messaging() .LoggingWith(new ConsoleLoggingMechanism {ShowInfo = false, ShowDebug = false}) .UsingFilePersistence() .ResolveReferencesWith(container) .RegisterHandlersFromContainer().BasedOn<IMessageConsumer>() .UsingHttpTransport() .AsAServer("SenderServer") .OpenChannel("TestRequest") .ForRequestReplySendingTo("TestReply@ReceiverServer") .WithDurability() .Sequenced() .Initialise(); do { Console.WriteLine("I am the sender. Press enter to send messages.."); Console.ReadLine(); Console.WriteLine("Sending messages"); for (int i = 0; i < 2001; i++) Bus.Send(new TestMessage("Hello" + i)); } while (true); }
public void ExpressionRegistrationCanBeChanged() { var container = new IocContainer(); var lifetime = new TransientLifetime(); var reg = new ExpressionRegistration<IFoo>(container, x => new Foo1(), lifetime, CompileMode.Delegate); Assert.AreSame(reg.Lifetime, lifetime); Assert.AreEqual(reg.CompileMode, CompileMode.Delegate); var get1 = reg.GetInstance(); var newLifetime = new ContainerLifetime(); var newCompileMode = CompileMode.Dynamic; // Set new lifetime reg.SetLifetime(newLifetime); Assert.AreSame(reg.Lifetime, newLifetime); // Set different compile mode reg.SetCompileMode(newCompileMode); Assert.AreEqual(reg.CompileMode, newCompileMode); var get2 = reg.GetInstance(); var get3 = reg.GetInstance(); // Check that the lifetime is also being used Assert.AreNotSame(get1, get2); Assert.AreSame(get2, get3); }
public void RegisterInstanceCanRegisterAStruct() { // Struct / ValueType ? using (var container = new IocContainer()) { int number = 32; var reg1 = container.RegisterInstance(typeof(int), number); var reg2 = container.RegisterInstance(number, "key"); // Check registrations Assert.IsInstanceOfType(reg1, typeof(InstanceRegistration<int>)); Assert.IsInstanceOfType(reg2, typeof(InstanceRegistration<int>)); Assert.AreSame(reg1.ReturnType, typeof(int)); Assert.AreSame(reg2.ReturnType, typeof(int)); // Check index Assert.IsTrue(container.Index.Contains(typeof(int))); Assert.IsTrue(container.Index.Contains(typeof(int), "key")); // Try to resolve var result1 = (int)container.Resolve(typeof(int)); var result2 = container.Resolve<int>("key"); Assert.AreEqual(number, result1); Assert.AreEqual(number, result2); Assert.AreEqual(result1, result2); } }
public Listeners(XDMessagingClient client, IocContainer container) : base(container) { Validate.That(client).IsNotNull(); this.client = client; }
public void CanSetDefaultLifetimeToRequestLifetime() { using (var container = new IocContainer(() => new RequestLifetime())) { Assert.IsInstanceOfType(container.DefaultLifetimeFactory(), typeof(RequestLifetime)); } }
public void TryResolveAllReturnsExpectedInstances() { using (var container = new IocContainer()) { // Arrange var foo1 = new Foo1(); var foo2 = new Foo2(); var foo3 = new Foo2(); var bar1 = new Bar1(); container.RegisterInstance<IFoo>(foo1); container.RegisterInstance<IFoo>("Foo1", foo2); container.RegisterInstance<IFoo>("Foo2", foo3); container.RegisterInstance<IBar>(bar1); // Act var results = container.TryResolveAll<IFoo>(); var resultList = results.ToList(); // Assert Assert.IsTrue(results.Count() == 3); CollectionAssert.Contains(resultList, foo1); CollectionAssert.Contains(resultList, foo2); CollectionAssert.Contains(resultList, foo3); } }
public void RequestLifetimeReturnsSameInstanceForSameRequest() { // Arrange using (var container = new IocContainer()) { var context1 = new FakeHttpContext("Http://fakeUrl1.com"); var context2 = new FakeHttpContext("Http://fakeUrl2.com"); HttpContextBase currentContext = null; var lifetime = new RequestLifetime(() => currentContext); // better solution for injecting HttpContext ? container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime); // Act currentContext = context1; var result1 = container.Resolve<IFoo>(); var result2 = container.Resolve<IFoo>(); currentContext = context2; var result3 = container.Resolve<IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
public void GetRegistrationsByNameThrowsExceptionIfRegistrationDoesntExist() { using (var container = new IocContainer()) { container.Index.Get(typeof(IFoo), "Foo"); } }
public void GetContainerTest() { var container = new IocContainer(); var s = new SimpleCommandModelContainerProvider(container); Assert.NotNull(s.Container); Assert.Equal(container, s.Container); }
public void GetGenericUsingKeyThrowsExceptionIfRegistrationDoesntExist() { using (var container = new IocContainer()) { container.Index.Get<IFoo>("Foo"); } }
public void Set_Test() { var locator = new IocContainer(); using(var builder = new ServiceBuilder(locator)) { var binder = builder.Use(Types.String); Assert.IsType<TypeServiceBinder>(binder); Assert.True(binder.Overwrite); Assert.Equal(Types.String, binder.ExpectType); Assert.Equal(binder, builder.TypeBinders.Value[0]); var binder2 = builder.Use("abc"); Assert.IsType<ValueServiceBinder>(binder2); Assert.Equal("abc", binder2.Name); Assert.Null(binder2.ExpectType); Assert.Equal(binder2, builder.ValueBinders.Value[0]); var binder3 = builder.Use(Types.String, "abc"); Assert.IsType<ValueServiceBinder>(binder3); Assert.Equal("abc", binder3.Name); Assert.Equal(Types.String, binder3.ExpectType); Assert.Equal(binder3, builder.ValueBinders.Value[1]); } }
public void IndexReturnsEmptyEnumerableWhenEmpty() { using (var container = new IocContainer()) { Assert.IsFalse(container.Index.Any()); } }
static void Main(string[] args) { var container = new IocContainer(); container.RegisterFromAssemblyOf<Program>(); Configure.Messaging() .LoggingWith(new ConsoleLoggingMechanism { ShowDebug = false }) .ResolveReferencesWith(container) .RegisterHandlersFromContainer().BasedOn<IMessageHandler>() .UsingHttpTransport() .AsAServer("OtherSenderServer") .AuthenticateToServer("ReceiverServer") .WithRequest<AuthenticationRequest>() .OnExpiry(s => Console.WriteLine("Session expired: {0}", s)) .OpenChannel("OtherTestRequest") .ForRequestReplySendingTo("TestReply@ReceiverServer") .WithDurability() .Initialise(); Console.WriteLine("I am the sender. Whats the password? (its 'Hello')"); string password = Console.ReadLine(); Bus.SendDirect(new AuthenticationRequest { Password = password }, new AuthenticationHandler(), exception => { }); do { Console.WriteLine("I am the sender. Press enter to send messages.."); Console.ReadLine(); Console.WriteLine("Sending messages"); Bus.Send(new TestMessage("Hello")); } while (true); }
static void Main(string[] args) { var container = new IocContainer(); container.RegisterFromAssemblyOf<Program>(); Configure.Messaging() .LoggingWith(new ConsoleLoggingMechanism { ShowInfo = false }) .ResolveReferencesWith(container) .RegisterHandlersFromContainer().BasedOn<IMessageConsumer>() .UsingFilePersistence() .UsingHttpTransport() .AsAServer("Server") .OpenChannel("TestSenderA") .ForRequestReplySendingTo("TestRecieverA@ServerA") .OnlyForMessages().WithNamePattern("Channel1") .WithDurability() .Sequenced() .OpenChannel("TestSenderB") .ForRequestReplySendingTo("TestRecieverB@ServerB") .OnlyForMessages().WithNamePattern("Channel2") .WithDurability() .Sequenced() .Initialise(); do { Console.WriteLine("I am the sender. Press A to send messages to reciever A, press B to send messages to reciever B.."); ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.A) { Console.WriteLine("Sending messages to GetChannel A"); Bus.Send(new Channel1Request("GetChannel A Hello")); Bus.Send(new Channel1Request("GetChannel A Hello1")); Bus.Send(new Channel1Request("GetChannel A Hello2")); Bus.Send(new Channel1Request("GetChannel A Hello3")); Bus.Send(new Channel1Request("GetChannel A Hello4")); Bus.Send(new Channel1Request("GetChannel A Hello5")); Bus.Send(new Channel1Request("GetChannel A Hello6")); Bus.Send(new Channel1Request("GetChannel A Hello7")); } if (key.Key == ConsoleKey.B) { Console.WriteLine("Sending messages to GetChannel B"); Bus.Send(new Channel2Request("GetChannel B Hello")); Bus.Send(new Channel2Request("GetChannel B Hello1")); Bus.Send(new Channel2Request("GetChannel B Hello2")); Bus.Send(new Channel2Request("GetChannel B Hello3")); Bus.Send(new Channel2Request("GetChannel B Hello4")); Bus.Send(new Channel2Request("GetChannel B Hello5")); Bus.Send(new Channel2Request("GetChannel B Hello6")); Bus.Send(new Channel2Request("GetChannel B Hello7")); } } while (true); }
public void RegisterInstanceGenericUsingKeyThatAlreadyExistsThrowsException() { using (var container = new IocContainer()) { container.RegisterInstance<IFoo>(new Foo1(), "Bar"); container.RegisterInstance<IFoo>(new Foo2(), "Bar"); } }
public void RegisterInstanceByTypeThrowsExceptionIfInstanceNotOfExpectedType() { using (var container = new IocContainer()) { var fooInstance = new Foo1(); var result = container.RegisterInstance(typeof(IBar), fooInstance); } }
public void RegisterThrowsExceptionIfRegistrationAlreadyExists() { using (var container = new IocContainer()) { container.Register<IFoo>(c => new Foo1()); container.Register<IFoo>(c => new Foo2()); } }
protected AppBootstrapper(Type startupPageType) { _startupPageType = startupPageType; Container = new IocContainer(); ViewModelMap = new ViewModelMap(); InitContainer(); InitCore(); }
private static void SetValueBinder(IocContainer container, ValueServiceBinder item) { var type = item.ExpectType ?? EmptyType; container.CacheTypeName.AddOrUpdate(type, t => { var dict = new ConcurrentDictionary <string, ICallSite>(StringComparer.CurrentCultureIgnoreCase); dict[item.Name] = item.CallSite; return(dict); }, (t, dict) => { dict[item.Name] = item.CallSite; return(dict); }); }
private static void SetTypeBinder(IocContainer container, TypeServiceBinder item) { container.CacheType.AddOrUpdate(item.ExpectType, t => new List <ICallSite>(1) { item.CallSite }, (t, list) => { if (item.Overwrite) { list.Clear(); } list.Insert(0, item.CallSite); list.TrimExcess(); return(list); }); }
private static void AppendToContainer(IocContainer container, ServiceBuilder builder) { if (builder.TypeBinders.IsValueCreated) { foreach (var item in builder.TypeBinders.Value) { SetTypeBinder(container, item); } } if (builder.ValueBinders.IsValueCreated) { foreach (var item in builder.ValueBinders.Value) { SetValueBinder(container, item); } } }
static IEnumerable <ICallSite> GetCallSites(IocContainer container, Type expectType) { List <ICallSite> callSites; if (container.FindCallSites(expectType, out callSites)) { foreach (var item in callSites.ToArray()) { yield return(item); } } if (container._hasParent) { foreach (var item in GetCallSites(container.Parent, expectType)) { yield return(item); } } yield break; }