/// <summary> /// Loads the main job configuration. /// </summary> /// <param name="unityContainer">The container to register to.</param> protected virtual void LoadConfiguration(IUnityContainer unityContainer) { if (PersistenceSupport) { var tablePrefix = ConfigurationManager.AppSettings[AbstractDbBatchMetadataDao.TablePrefixSetting]; var injectionMembers = new InjectionMember[tablePrefix == null ? 1 : 2]; injectionMembers[0] = new InjectionProperty("ConnectionStringSettings", new ResolvedParameter <ConnectionStringSettings>("Default")); if (tablePrefix != null) { injectionMembers[1] = new InjectionProperty("TablePrefix", tablePrefix); } unityContainer.RegisterSingletonWithFactory <IJobRepository, DbJobRepositoryFactory>(injectionMembers); unityContainer.RegisterSingletonWithFactory <IJobExplorer, DbJobExplorerFactory>(injectionMembers); } else { unityContainer.RegisterSingletonWithFactory <IJobRepository, MapJobRepositoryFactory>(); unityContainer.RegisterSingletonWithFactory <IJobExplorer, MapJobExplorerFactory>(); } unityContainer.RegisterSingleton <IJobOperator, SimpleJobOperator>(new InjectionProperty("JobLauncher"), new InjectionProperty("JobRepository"), new InjectionProperty("JobExplorer"), new InjectionProperty("JobRegistry")); unityContainer.RegisterSingleton <IJobLauncher, SimpleJobLauncher>(new InjectionProperty("JobRepository")); unityContainer.RegisterSingleton <IListableJobLocator, MapJobRegistry>(); unityContainer.RegisterSingleton <IJobParametersIncrementer, RunIdIncrementer>(); unityContainer.RegisterSingleton <ITaskExecutor, SimpleAsyncTaskExecutor>(); }
public virtual void ToStringTest(InjectionMember member, MemberInfo _) { // Arrange var set = new PolicySet(); var cast = set as IPolicySet; // Act var debugCold = ToStringMethod.Invoke(member, new object[] { true }) as string; var optimized = ToStringMethod.Invoke(member, new object[] { false }) as string; // Validate Assert.IsFalse(string.IsNullOrWhiteSpace(optimized)); Assert.IsFalse(string.IsNullOrWhiteSpace(debugCold)); Assert.IsTrue(debugCold.StartsWith(member.GetType().Name)); // Act member.AddPolicies <IResolveContext, IPolicySet>(typeof(IPolicySet), typeof(PolicySet), null, ref cast); var debugInitialzed = ToStringMethod.Invoke(member, new object[] { true }) as string; var initialized = ToStringMethod.Invoke(member, new object[] { false }) as string; // Validate Assert.IsFalse(string.IsNullOrWhiteSpace(debugInitialzed)); Assert.IsFalse(string.IsNullOrWhiteSpace(initialized)); Assert.AreNotEqual(debugCold, debugInitialzed); Assert.AreNotEqual(optimized, initialized); }
public virtual void HashCodeCold(InjectionMember member, MemberInfo _) { // Act var hash = member.GetHashCode(); // Validate Assert.AreEqual(0, hash); }
public virtual void AddWrongTypeTest(InjectionMember member, MemberInfo _) { // Arrange var set = new PolicySet(); var cast = set as IPolicySet; // Act member.AddPolicies <IResolveContext, IPolicySet>(typeof(WrongType), typeof(WrongType), null, ref cast); }
public InterceptionStrategy() { IUnityContainer container = new UnityContainer(); UnityContainerConfigurator configurator = new UnityContainerConfigurator(container); EnterpriseLibraryContainer.ConfigureContainer(configurator, ConfigurationSourceFactory.Create()); this.UnityContainer = container; this.InterceptionMember = new InstanceInterceptionPolicySettingInjectionMember(new TransparentProxyInterceptor()); }
public virtual void EqualsObjectTest(InjectionMember member, MemberInfo info) { // Arrange var set = new PolicySet(); var cast = set as IPolicySet; // Act member.AddPolicies <IResolveContext, IPolicySet>(typeof(IPolicySet), typeof(PolicySet), null, ref cast); // Validate Assert.IsTrue(member.Equals(info)); }
public virtual void NoAddedPoliciesTest(InjectionMember member, MemberInfo _) { // Arrange var set = new PolicySet(); var cast = set as IPolicySet; // Act member.AddPolicies <IResolveContext, IPolicySet>(typeof(IPolicySet), typeof(PolicySet), null, ref cast); // Validate Assert.AreEqual(0, set.Count); }
public virtual void HashCodeTest(InjectionMember member, MemberInfo _) { // Arrange var set = new PolicySet(); var cast = set as IPolicySet; member.AddPolicies <IResolveContext, IPolicySet>(typeof(IPolicySet), typeof(PolicySet), null, ref cast); // Act var hash = member.GetHashCode(); // Validate Assert.AreNotEqual(0, hash); }
private void ConfigureNotificationPipes() { var appSettings = _container.Resolve <AppSettings>(); _container.Resolve <IRulesConfig>().GetRedirectionMap(); var redirector = new Redirector(_container.Resolve <IRulesConfig>().GetRedirectionMap(), appSettings.Supervisors, appSettings.Maintainers); _container.RegisterInstance(redirector); var commonProperties = new InjectionMember[] { new InjectionProperty("Redirector", new InjectionParameter <Redirector>(redirector)), new InjectionProperty("LogoFileName", new InjectionParameter <string>(appSettings.LogoFileName)), new InjectionProperty("Messenger", new InjectionParameter <IMessenger>(_container.Resolve <IMessenger>())), new InjectionProperty("HttpHandler", new InjectionParameter <IHttpHandler>(_container.Resolve <IHttpHandler>())) }; _container.RegisterType <ReactionPipe <Issue> >("Jql", commonProperties.Union( new[] { new InjectionProperty("PackageSupplier", _container.Resolve <IPackageSupplier>("Jql")), new InjectionProperty("PackageConverter", _container.Resolve <IPackageConverter <Issue> >()) }) .ToArray() ); _container.RegisterType <ReactionPipe <Issue> >("Structure", commonProperties.Union( new[] { new InjectionProperty("PackageSupplier", _container.Resolve <IPackageSupplier>("Structure")), new InjectionProperty("PackageConverter", _container.Resolve <IPackageConverter <Issue> >()) }) .ToArray() ); _container.RegisterType <ReactionPipe <Build> >( commonProperties.Union( new[] { new InjectionProperty("PackageSupplier", _container.Resolve <IPackageSupplier>()), new InjectionProperty("PackageConverter", _container.Resolve <IPackageConverter <Build> >()) }) .ToArray() ); }
public static IUnityContainer RegisterChannelFactory <TChannel>(this IUnityContainer container, string bindingName, string endpointName, string clientName) { var injectionMembers = new InjectionMember[] { new InjectionConstructor( new ResolvedParameter <Binding>(bindingName), new ResolvedParameter <EndpointAddress>(endpointName) ) }; InnerRegisterChannelFactory <TChannel>(container, clientName, injectionMembers); return(container); }
public void PerformRegistrations_CreatesAllParts_RegistersItIntoUnity() { var lifetimeManager = new ContainerControlledLifetimeManager(); var injectionMembers = new InjectionMember[] { new InterceptionBehavior <PolicyInjectionBehavior>() }; StubCreateInjectionMembers(injectionMembers); registrationNameFactory.Setup(f => f.GetRegistrationName(It.IsAny <TypeMapping>())).Returns("TEST"); configLifetimeManagerFactory.Setup(l => l.CreateLifetimeManager(It.IsAny <TypeMapping>())).Returns(lifetimeManager); // Act handler.PerformRegistrations(target.Object, new[] { new TypeMapping(typeof(String), typeof(Boolean)) }); // Assert target.Verify(t => t.RegisterType(typeof(String), typeof(Boolean), "TEST", lifetimeManager, injectionMembers)); }
public static IUnityContainer RegisterChannelFactory <TChannel>(this IUnityContainer container, string name, Binding binding, EndpointAddress endpointAddress) { var injectionMembers = new InjectionMember[] { new InjectionConstructor( new InjectionParameter <Binding>(binding), new InjectionParameter <EndpointAddress>(endpointAddress) ) }; InnerRegisterChannelFactory <TChannel>(container, name, injectionMembers); return(container); }
private InjectionMember[] GetInjectionMembers(IInterceptionBehavior[] interceptors) { InjectionMember[] injectionMember = null; if (interceptors != null && interceptors.Length > 0) { injectionMember = new InjectionMember[interceptors.Length + 1]; injectionMember[0] = new Interceptor <VirtualMethodInterceptor>(); for (int i = 0; i < interceptors.Length; i++) { injectionMember[i + 1] = new InterceptionBehavior(interceptors[i]); } } return(injectionMember); }
/// <summary> /// 装载一批动态的类型 /// Author:zhangzhanling /// Date:2015-04-03 /// </summary> private void LoadDynamicType(IUnityContainer _container) { //unity动态类型注入,各个程序集用,分开,支持*通配符号 string unityDynamicAssembly = System.Configuration.ConfigurationManager.AppSettings["unityDynamicAssembly"]; //是否同时启动数据集缓存策略 string unityCachingDoing = System.Configuration.ConfigurationManager.AppSettings["unityCachingDoing"]; InjectionMember[] injectionMembers = new InjectionMember[] { }; if (unityCachingDoing == "1") { injectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>() }; } if (!string.IsNullOrWhiteSpace(unityDynamicAssembly)) { Array.ForEach(unityDynamicAssembly.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), dllName => { var baseDir = AppDomain.CurrentDomain.BaseDirectory; if (System.Web.HttpContext.Current != null) { baseDir += "bin"; } var files = Directory.GetFiles(baseDir, dllName); var iTypes = new List <Type>(); foreach (var file in files) { var interfaceASM = Assembly.LoadFrom(Path.Combine(baseDir, file)); var types = from t in interfaceASM.GetTypes() where !string.IsNullOrWhiteSpace(t.Namespace) select t; foreach (var type in types) { if (type.GetInterfaces() != null && type.GetInterfaces().Any()) { foreach (var father in type.GetInterfaces()) { _container.RegisterType(father , type , injectionMembers); } } } } }); } }
/// <summary>Registers the type mappings with the Unity container.</summary> /// <param name="container">The unity container to configure.</param> /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks> private static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. // container.LoadConfiguration(); container.RegisterType <IDbContextStorage, HttpDbContextStorage>(new ContainerControlledLifetimeManager()); container.RegisterType(typeof(IDbContextProvider <>), typeof(SimpleDbContextProvider <>), new TransientLifetimeManager()); container.RegisterType <ITypeFinder, TypeFinder>(new ContainerControlledLifetimeManager()); //var repoAssemblies = AllClasses.FromAssemblies(Assembly.Load("Qxr.Tests.Repositories")).Where(t => typeof(IDependency).IsAssignableFrom(t)); //var serviceAssemblies = AllClasses.FromAssemblies(Assembly.Load("Qxr.Services")).Where(t => typeof(IDependency).IsAssignableFrom(t)); var repoAssemblies = AllClasses.FromAssemblies(Assembly.Load("Qxr.Tests.Repositories")).Where(t => t.Name.EndsWith("Repository")); var serviceAssemblies = AllClasses.FromAssemblies(Assembly.Load("Qxr.Services")).Where(t => t.Name.EndsWith("Service")); var allAssemblies = repoAssemblies.Concat(serviceAssemblies).ToList(); container.RegisterType <ILogger, Log4NetAdapter>(new ContainerControlledLifetimeManager()); var interceptionInjectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <AuditLoggingBehavior>() }; container.RegisterTypes(allAssemblies, WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.Transient, t => interceptionInjectionMembers); container.RegisterType(typeof(IReadOnlyRepository <>), typeof(QxrTestRepositoryBase <>), interceptionInjectionMembers); container.RegisterType(typeof(IRepository <>), typeof(QxrTestRepositoryBase <>), interceptionInjectionMembers); container.RegisterType <IUnitOfWork, QxrTestUnitOfWork>(interceptionInjectionMembers); //var loggerTypes = allAssemblies.Where(t => t.GetProperties().Any(c => c.PropertyType == typeof(ILogger))); //container.RegisterTypes(loggerTypes, // WithMappings.FromMatchingInterface, // WithName.Default, // WithLifetime.Transient, t => new InjectionMember[] // { // new InjectionProperty("Logger") // }); container.RegisterType <IIocResolver, IocResolver>(new InjectionConstructor(container)); DbContextProviderFactory.Initialize(container.Resolve <IIocResolver>()); LoggingFactory.Initialize(container.Resolve <ILogger>()); new AutoMapperBootstrap(container.Resolve <ITypeFinder>()).CreateMappings(); }
private void RegistrarMapeamento(Mapeamento mapeamento, bool sobreescrever) { if (string.IsNullOrEmpty(mapeamento.Nome)) { if (!sobreescrever && UnityContainerExtensions.IsRegistered(this._container, mapeamento.De)) { throw new Exception($"Já existe registro de mapeamento para este tipo ( {mapeamento.De.FullName} ), verifique o tipo ou faça o registro explicitando um nome."); } InjectionMember[] memberArray1 = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapeamento.De, mapeamento.Para, memberArray1); } else { if (!sobreescrever && UnityContainerExtensions.IsRegistered(this._container, mapeamento.De)) { throw new Exception($"Já existe registro de mapeamento nomeado para este tipo ( {mapeamento.De.FullName} ), verifique o tipo."); } InjectionMember[] memberArray2 = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapeamento.De, mapeamento.Para, mapeamento.Nome, memberArray2); } }
private void RegisterMapping(Mapping mapping, bool writeOver) { if (string.IsNullOrEmpty(mapping.Name)) { if (!writeOver && UnityContainerExtensions.IsRegistered(this._container, mapping.From)) { throw new Exception($"Já existe registro de mapeamento para este tipo ( {mapping.From.FullName} ), verifique o tipo ou faça o registro explicitando um nome."); } InjectionMember[] injectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapping.From, mapping.To, injectionMembers); } else { if (!writeOver && UnityContainerExtensions.IsRegistered(this._container, mapping.From)) { throw new Exception($"Já existe registro de mapeamento nomeado para este tipo ( {mapping.From.FullName} ), verifique o tipo."); } InjectionMember[] injectionMembers = new InjectionMember[] { new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <PolicyInjectionBehavior>() }; UnityContainerExtensions.RegisterType(this._container, mapping.From, mapping.To, mapping.Name, injectionMembers); } }
internal static void RegisterNavigationManager([NotNull] this IUnityContainer unityContainer, [NotNull] object frameControl, [NotNull] INavigationManagerTypeProvider navigationManagerTypeProvider, [NotNull] IFrameControlTypeProvider frameControlTypeProvider) { if (navigationManagerTypeProvider == null) { throw new ArgumentNullException(nameof(navigationManagerTypeProvider)); } if (frameControlTypeProvider == null) { throw new ArgumentNullException(nameof(frameControlTypeProvider)); } var navigationManagerType = navigationManagerTypeProvider.GetNavigationManagerType(); if (navigationManagerType == null) { throw new InvalidOperationException(ExceptionMessages.NavigationManagerTypeIsNotFound()); } var frameControlType = frameControlTypeProvider.GetFrameControlType(navigationManagerType); if (frameControlType == null) { throw new InvalidOperationException(ExceptionMessages.FrameControlTypeIsNotFound()); } unityContainer.RegisterInstance(frameControlType, NavigationManagerCtorInfo.Args.FrameControl.Name, frameControl); var injectionMembers = new InjectionMember[] { NavigationManagerCtorInfo.GetInjectionConstructor(frameControlType) }; unityContainer.RegisterNavigationManager(frameControl, navigationManagerType, frameControlType, injectionMembers); }
/// <summary> /// Resolves the binding. /// </summary> /// <param name="binding">Binding to be resolved.</param> /// <param name="type">Binding type.</param> /// <param name="member">Member for which the binding is being resolved.</param> /// <param name="parentInstance">Parent object in which the resolve is occuring.</param> /// <param name="identifier">The binding identifier to be looked for.</param> /// <returns>The resolved instance from the binding.</returns> protected object ResolveBinding(BindingInfo binding, Type type, InjectionMember member, object parentInstance, object identifier) { //Condition evaluation. if (binding.condition != null) { var context = new InjectionContext() { member = member, memberType = type, identifier = identifier, parentType = (parentInstance != null ? parentInstance.GetType() : null), parentInstance = parentInstance, injectType = binding.type }; if (!binding.condition(context)) { return(null); } } //Identifier evaluation. bool resolveByIdentifier = identifier != null; bool bindingHasIdentifier = binding.identifier != null; if ((!resolveByIdentifier && bindingHasIdentifier) || (resolveByIdentifier && !bindingHasIdentifier) || (resolveByIdentifier && bindingHasIdentifier && !binding.identifier.Equals(identifier))) { return(null); } //Instance evaluation. object instance = null; if (this.bindingEvaluation != null) { var delegates = this.bindingEvaluation.GetInvocationList(); for (int delegateIndex = 0; delegateIndex < delegates.Length; delegateIndex++) { instance = ((BindingEvaluationHandler)delegates[delegateIndex]).Invoke(this, ref binding); } } if (instance == null) { if (binding.instanceType == BindingInstance.Transient) { instance = this.Instantiate(binding.value as Type); } else if (binding.instanceType == BindingInstance.Factory) { var context = new InjectionContext() { member = member, memberType = type, identifier = identifier, parentType = (parentInstance != null ? parentInstance.GetType() : null), parentInstance = parentInstance, injectType = binding.type }; instance = (binding.value as IFactory).Create(context); } else { //Binding is a singleton object. //If the binding value is a type, instantiate it. if (binding.value is Type) { binding.value = this.Instantiate(binding.value as Type); } instance = binding.value; } } if (this.bindingResolution != null) { this.bindingResolution(this, ref binding, ref instance); } return(instance); }
/// <summary> /// Resolves an instance for a specified type at a certain member in an instance with a given identifier. /// </summary> /// <param name="type">Binding type.</param> /// <param name="member">Member for which the binding is being resolved.</param> /// <param name="parentInstance">Parent object in which the resolve is occuring.</param> /// <param name="identifier">The binding identifier to be looked for.</param> protected object Resolve(Type type, InjectionMember member, object parentInstance, object identifier) { object resolution = null; if (this.beforeResolve != null) { var delegates = this.beforeResolve.GetInvocationList(); for (int delegateIndex = 0; delegateIndex < delegates.Length; delegateIndex++) { var continueExecution = ((TypeResolutionHandler)delegates[delegateIndex]).Invoke(this, type, member, parentInstance, identifier, ref resolution); if (!continueExecution) { return(resolution); } } } //Array is used for multiple injection. //So, when the type is an array, the type to be read from the bindings list is the element type. Type typeToGet; IList <BindingInfo> bindings; if (type == null) { typeToGet = typeof(object); //If no type is provided, look for bindings by identifier. bindings = this.binder.GetBindingsFor(identifier); } else { if (type.IsArray) { typeToGet = type.GetElementType(); } else { typeToGet = type; } //If a type is provided, look for bindings by identifier. bindings = this.binder.GetBindingsFor(typeToGet); } IList <object> instances = new List <object>(); if (bindings == null) { instances.Add(this.Instantiate(type as Type)); } else { for (int bindingIndex = 0; bindingIndex < bindings.Count; bindingIndex++) { var binding = bindings[bindingIndex]; var instance = this.ResolveBinding(binding, type, member, parentInstance, identifier); if (instance != null) { instances.Add(instance); } } } if (type != null && !type.IsArray && instances.Count == 1) { resolution = instances[0]; } else if (instances.Count > 0) { var array = Array.CreateInstance(typeToGet, instances.Count); for (int listIndex = 0; listIndex < instances.Count; listIndex++) { array.SetValue(instances[listIndex], listIndex); } resolution = array; } if (this.afterResolve != null) { var delegates = this.afterResolve.GetInvocationList(); for (int delegateIndex = 0; delegateIndex < delegates.Length; delegateIndex++) { var continueExecution = ((TypeResolutionHandler)delegates[delegateIndex]).Invoke(this, type, member, parentInstance, identifier, ref resolution); if (!continueExecution) { return(resolution); } } } return(resolution); }
/// <summary> /// Gets parameters from a collection of <see cref="Adic.Cache.ParameterInfo"/>. /// </summary> /// <param name="instance">The instance to have its dependencies resolved.</param> /// <param name="parametersInfo">Parameters info collection.</param> /// <param name="injectionMember">The member in which the injection is taking place.</param> /// <returns>The parameters.</returns> protected object[] GetParametersFromInfo(object instance, ParameterInfo[] parametersInfo, InjectionMember injectionMember) { object[] parameters = new object[parametersInfo.Length]; for (int paramIndex = 0; paramIndex < parameters.Length; paramIndex++) { var parameterInfo = parametersInfo[paramIndex]; parameters[paramIndex] = this.Resolve(parameterInfo.type, injectionMember, parameterInfo.name, instance, parameterInfo.identifier, false); } return(parameters); }
public virtual void BuildRequiredTest(InjectionMember member, MemberInfo _) { // Validate Assert.IsTrue(member.BuildRequired); }
private void MapInjectionMember(ref InjectionMember[] injectionMembers, object injectionObjects) { var tmp = injectionObjects as InjectedMember; if (tmp == null || tmp.InjectionOjects.Count == 0) { return; } else { injectionMembers = new InjectionMember[tmp.InjectionOjects.Count]; } if (tmp.MemberType == InjectionMemberType.Constructor) { for (int i = 0; i < tmp.InjectionOjects.Count; i++) { var c = new InjectionConstructor(tmp.InjectionOjects[0]); injectionMembers[i] = c; } } if (tmp.MemberType == InjectionMemberType.Method) { for (int i = 0; i < tmp.InjectionOjects.Count; i++) { injectionMembers[i] = tmp.InjectionOjects[0] as InjectionMember; } } if (tmp.MemberType == InjectionMemberType.Property) { for (int i = 0; i < tmp.InjectionOjects.Count; i++) { injectionMembers[i] = tmp.InjectionOjects[0] as InjectionMember; } } //foreach (var obj in injectionObjects) //{ // InjectionMember member = default(InjectionMember); // if (obj is InjectionConstructor) // { // var tmp = obj as InjectionConstructor; // if (tmp == null) // throw new Exception("对象转InjectionConstructor出错"); // member = new InjectionConstructor(tmp.ArgValues); // } // if (obj is InjectionProperty) // { // var tmp = obj as InjectionProperty; // if (tmp.Value == null) // member = new Microsoft.Practices.Unity.InjectionProperty(tmp.Name); // else // member = new Microsoft.Practices.Unity.InjectionProperty(tmp.Name, tmp.Value); // } // if (obj is InjectionMethod) // { // var tmp = obj as InjectionMethod; // member = new Microsoft.Practices.Unity.InjectionMethod(tmp.Name, tmp.ArgValues); // } // injectionMembers[i] = member; //} }
public virtual void EqualsObjectCold(InjectionMember member, MemberInfo info) { // Validate Assert.IsFalse(member.Equals(info)); }