bool IResolver.TryResolve(Type type, object tag, out object value) { if (tag == null) { var services = ServicesByType.GetOrAdd(type, t => Services(t).Distinct().ToArray()); for (int index = 0; index < services.Count; ++index) { var serviceType = services[index]; var service = new KeyedService(FiberModule.Key_DoNotSerialize, serviceType); var registry = this.context.ComponentRegistry; IComponentRegistration registration; if (registry.TryGetRegistration(service, out registration)) { // Autofac will still generate "implicit relationship types" (e.g. Func or IEnumerable) // and ignore the key in KeyedService bool generated = registry.IsRegistered(new KeyedService(new object(), serviceType)); if (!generated) { value = this.context.ResolveComponent(registration, this.parameters); return(true); } } } } value = null; return(false); }
public void TestAutofacRegistrations() { IContainer container = ServicesContainer.Container; IEnumerable <IServiceWithType> autofacServices = container.ComponentRegistry.Registrations.SelectMany(x => x.Services).OfType <IServiceWithType>(); foreach (IServiceWithType svc in autofacServices) { Console.WriteLine("Resolving registration: '{0}'", svc); IServiceWithType serviceWithType = svc; Assert.DoesNotThrow(() => { KeyedService keyedService = serviceWithType as KeyedService; var resolvedService = keyedService != null ? container.ResolveKeyed(keyedService.ServiceKey, serviceWithType.ServiceType) : container.Resolve(serviceWithType.ServiceType); if (resolvedService == null) { throw new Exception("Autofac service not found: " + serviceWithType.ServiceType.Name); } }, $"Failed to resolve autofac service '{serviceWithType}' or one of it's dependencies" ); } }
/// <summary> /// /// </summary> public MultiEfRepository() { Type t = typeof(T); lock (t) { Service service = null; if (s_EntityKeyedServices.ContainsKey(t)) { service = s_EntityKeyedServices[t]; } else { var contextKeyAttribute = t.GetCustomAttribute <EntityContextKeyAttribute>(); if (contextKeyAttribute == null || contextKeyAttribute.ContextKey.IsEmpty()) { service = new TypedService(t); } else { service = new KeyedService(contextKeyAttribute.ContextKey, t); } s_EntityKeyedServices.Add(t, service); } _context = EngineContext.Current.ContainerManager.ResolveService <IChenyuanDBContext>(service); } }
bool IResolver.TryResolve(Type type, object tag, out object value) { if (tag == null) { var services = ServicesByType.GetOrAdd(type, t => Services(t).Distinct().ToArray()); for (int index = 0; index < services.Count; ++index) { var serviceType = services[index]; var service = new KeyedService(FiberModule.Key_DoNotSerialize, serviceType); var registry = this.context.ComponentRegistry; IComponentRegistration registration; if (registry.TryGetRegistration(service, out registration)) { if (IsAutoFacImplicit(serviceType)) { continue; } value = this.context.ResolveComponent(registration, this.parameters); return(true); } } } value = null; return(false); }
public IEnumerable <IComponentRegistration> RegistrationsFor( Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { KeyedService keyedService = service as KeyedService; if (keyedService == null || keyedService.ServiceKey.GetType() != typeof(String)) { yield break; } IComponentRegistration registration = RegistrationBuilder .ForDelegate(keyedService.ServiceType, (c, p) => { Type foosType = typeof(IEnumerable <>).MakeGenericType(keyedService.ServiceType); IEnumerable <IFoo> foos = (IEnumerable <IFoo>)c.Resolve(foosType); foos = foos.Where(f => f.AutoFactName == (String)keyedService.ServiceKey).ToArray(); if (foos.Count() == 0) { throw new Exception($"no Foo available for {keyedService.ServiceKey}"); } else if (foos.Count() > 1) { throw new Exception($"more than 1 Foo available for {keyedService.ServiceKey}"); } else { return(foos.First()); } }) .Named((String)keyedService.ServiceKey, keyedService.ServiceType) .CreateRegistration(); yield return(registration); }
/// <summary> /// 装配字段 /// </summary> /// <param name="property"></param> /// <param name="context"></param> /// <param name="Parameters"></param> /// <param name="instance"></param> /// <param name="allowCircle"></param> /// <returns></returns> public object ResolveField(FieldInfo property, IComponentContext context, IEnumerable <Parameter> Parameters, object instance, bool allowCircle) { if (!allowCircle) { return(property == null ? null : Resolve(property.DeclaringType, property.FieldType, context, "field")); } if (context == null) { throw new ArgumentNullException(nameof(context)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } Service propertyService = null; if (!string.IsNullOrEmpty(this.Name)) { propertyService = new KeyedService(this.Name, property.FieldType); } else { propertyService = new TypedService(property.FieldType); } if (Parameters != null && Parameters.Count() == 1) { if (!(Parameters.First() is AutowiredParmeter AutowiredParmeter)) { return(null); } if (AutowiredParmeter.AutowiredChains.TryGetValue(property.FieldType.FullName, out var objectInstance)) { return(objectInstance); } else { AutowiredParmeter.Add(property.DeclaringType.FullName, instance); if (context.TryResolveService(propertyService, new Parameter[] { AutowiredParmeter }, out var propertyValue)) { return(propertyValue); } } } else { var instanceTypeParameter = new AutowiredParmeter(); instanceTypeParameter.Add(property.DeclaringType.FullName, instance); if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue)) { return(propertyValue); } } return(null); }
public void ChangeType_ProvidesKeyedServiceWithNewTypeAndSameKey() { var newType = typeof(string); var key = new object(); var service = new KeyedService(key, typeof(object)); var changedService = service.ChangeType(newType); Assert.Equal(new KeyedService(key, newType), changedService); }
public void SetUp() { _modelMapper = new ModelMapper(); TypeModel unused; _modelMapper.GetOrAddTypeModel(typeof(string), out unused); _service = new KeyedService(new object(), typeof(string)); _mapped = _modelMapper.GetServiceModel(_service); }
internal object Resolve(IComponentContext context, object instance, Type classType, Type memberType, IEnumerable <Parameter> Parameters) { if ((typeof(IObjectFactory).IsAssignableFrom(memberType))) { return(context.Resolve <ObjectBeanFactory>().CreateAutowiredFactory(this, memberType, classType, instance, Parameters)); } Service propertyService = null; if (!string.IsNullOrEmpty(this.Name)) { propertyService = new KeyedService(this.Name, memberType); } else { propertyService = new TypedService(memberType); } // ReSharper disable once PossibleMultipleEnumeration if (Parameters != null && Parameters.Count() == 1) { // ReSharper disable once PossibleMultipleEnumeration if (!(Parameters.First() is AutowiredParmeter AutowiredParmeter)) { return(null); } // ReSharper disable once AssignNullToNotNullAttribute if (AutowiredParmeter.TryGet(getAutowiredParmeterKey(memberType), out var objectInstance)) { return(objectInstance); } else { // ReSharper disable once PossibleNullReferenceException AutowiredParmeter.TryAdd(getAutowiredParmeterKey(classType), instance); if (context.TryResolveService(propertyService, new Parameter[] { AutowiredParmeter }, out var propertyValue)) { return(propertyValue); } } } else { var instanceTypeParameter = new AutowiredParmeter(); // ReSharper disable once PossibleNullReferenceException instanceTypeParameter.TryAdd(getAutowiredParmeterKey(classType), instance); if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue)) { return(propertyValue); } } return(null); }
/// <summary> /// Tries to resolve an instance for the controller associated with a given service key for the work context scope. /// </summary> /// <typeparam name="T">The type of the controller.</typeparam> /// <param name="workContext">The work context.</param> /// <param name="serviceKey">The service key for the controller.</param> /// <param name="instance">The controller instance.</param> /// <returns>True if the controller was resolved; false otherwise.</returns> protected bool TryResolve<T>(WorkContext workContext, object serviceKey, out T instance) { if (workContext != null && serviceKey != null) { var key = new KeyedService(serviceKey, typeof (T)); object value; if (workContext.Resolve<ILifetimeScope>().TryResolveService(key, out value)) { instance = (T) value; return true; } } instance = default(T); return false; }
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { KeyedService keyedService = registration.Services .OfType <KeyedService>() .FirstOrDefault(ks => ks.ServiceType == typeof(TServiceType)); if (keyedService != null) { registration.Preparing += (sender, e) => { e.Parameters = e.Parameters.Concat( new Parameter[] { new NamedParameter(this._parameterName, keyedService.ServiceKey) }); }; } base.AttachToComponentRegistration(componentRegistry, registration); }
private static bool TryMapService(ExportDefinition ed, out Service service) { /* Issue 326: MEF is string based, not type-based, so when an export and * an import line up on contract (or type identity) it's always based on a * generated contract name rather than an actual type. Usually the contract * name and the type name are the same, just that the contract name is ONLY * the type name without any assembly qualifier. However, when you get to * generics, the type name gets mangled a bit. ITest<Foo> becomes ITest(Foo) * with parens instead of angle brackets. If you have multiple types with the * same name but in different assemblies, or nested types, things get even more * mangled. For this reason, you have to access the internal type-to-contract * map that MEF uses when building these items at runtime. Unfortunately, that's * not publicly exposed so we have to use reflection to reverse the lookup. * * Note we tried doing something like... * AppDomain.CurrentDomain.GetAssemblies() * .SelectMany(asm => asm.GetTypes()) * .SingleOrDefault(t => AttributedModelServices.GetContractName(t) == exportTypeIdentity) * * But that doesn't work because when you enumerate the types in the assemblies * you only get OPEN generics, and many types expose services that are CLOSED * generics. That means the lambda above still won't find the service and things * still won't get registered. */ var ct = FindType(ed.ContractName); if (ct != null) { service = new TypedService(ct); return(true); } var et = FindType((string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName]); if (et != null) { service = new KeyedService(ed.ContractName, et); return(true); } service = null; return(false); }
public void RespectsExplicitInterchangeServices() { var builder = new ContainerBuilder(); var catalog = new TypeCatalog(typeof(HasMultipleExports)); var interchangeService1 = new TypedService(typeof(HasMultipleExportsBase)); var interchangeService2 = new KeyedService("b", typeof(HasMultipleExports)); var nonInterchangeService1 = new TypedService(typeof(HasMultipleExports)); var nonInterchangeService2 = new KeyedService("a", typeof(HasMultipleExports)); builder.RegisterComposablePartCatalog(catalog, interchangeService1, interchangeService2); var container = builder.Build(); Assert.IsTrue(container.IsRegisteredService(interchangeService1)); Assert.IsTrue(container.IsRegisteredService(interchangeService2)); Assert.IsFalse(container.IsRegisteredService(nonInterchangeService1)); Assert.IsFalse(container.IsRegisteredService(nonInterchangeService2)); }
private Type GetImplementationType <T>(object key = null) { Autofac.Core.Service service; if (key == null) { service = new TypedService(typeof(T)); } else { service = new KeyedService(key, typeof(T)); } var types = container.ComponentRegistry.RegistrationsFor(service) .Select(x => x.Activator) .OfType <ReflectionActivator>() .Select(x => x.LimitType) .ToList(); Assert.AreEqual(1, types.Count); return(types.First()); }
public IEnumerable <IComponentRegistration> RegistrationsFor(Service service, Func <Service, IEnumerable <IComponentRegistration> > registrationAccessor) { var swt = service as IServiceWithType; KeyedService ks; if (swt == null || (ks = new KeyedService(fromKey, swt.ServiceType)) == service || !swt.ServiceType.IsGenericType || swt.ServiceType.GetGenericTypeDefinition() != decoratedType) { return(Enumerable.Empty <IComponentRegistration>()); } return(registrationAccessor(ks).Select(cr => new ComponentRegistration( Guid.NewGuid(), BuildActivator(cr, swt), cr.Lifetime, cr.Sharing, cr.Ownership, new[] { toKey != null ? (Service) new KeyedService(toKey, swt.ServiceType) : new TypedService(swt.ServiceType) }, cr.Metadata, cr))); }
/// <summary> /// The get controller session behavior. /// </summary> /// <param name="requestContext"> /// The request context. /// </param> /// <param name="controllerName"> /// The controller name. /// </param> /// <returns> /// The System.Web.SessionState.SessionStateBehavior. /// </returns> public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (string.IsNullOrEmpty(controllerName)) { throw new ArgumentNullException("controllerName"); } var keyedService = new KeyedService(controllerName.ToLowerInvariant(), typeof(IController)); IComponentRegistration registry; this.container.ComponentRegistry.TryGetRegistration(keyedService, out registry); if (registry != null) { return(this.GetControllerSessionBehavior(requestContext, registry.Activator.LimitType)); } return(this.defaultFactory.GetControllerSessionBehavior(requestContext, controllerName)); }
/// <summary>Check if service is registered</summary> public static bool IsRegisteredService(this IComponentContext context, KeyedService ks) => context.Container.IsRegistered(ks.ServiceType, ks.ServiceKey);
/// <summary> /// 装配字段 /// </summary> /// <param name="property"></param> /// <param name="context"></param> /// <param name="Parameters"></param> /// <param name="instance"></param> /// <param name="allowCircle"></param> /// <returns></returns> public object ResolveField(FieldInfo property, IComponentContext context, IEnumerable <Parameter> Parameters, object instance, bool allowCircle) { if (property == null) { throw new ArgumentNullException(nameof(property)); } if (!allowCircle) { return(Resolve(property.DeclaringType, property.FieldType, context, "field")); } if (context == null) { throw new ArgumentNullException(nameof(context)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } Service propertyService = null; if (!string.IsNullOrEmpty(this.Name)) { propertyService = new KeyedService(this.Name, property.FieldType); } else { propertyService = new TypedService(property.FieldType); } // ReSharper disable once PossibleMultipleEnumeration if (Parameters != null && Parameters.Count() == 1) { // ReSharper disable once PossibleMultipleEnumeration if (!(Parameters.First() is AutowiredParmeter AutowiredParmeter)) { return(null); } // ReSharper disable once AssignNullToNotNullAttribute if (AutowiredParmeter.TryGet(getAutowiredParmeterKey(property.FieldType), out var objectInstance)) { return(objectInstance); } else { // ReSharper disable once PossibleNullReferenceException AutowiredParmeter.TryAdd(getAutowiredParmeterKey(property.DeclaringType), instance); if (context.TryResolveService(propertyService, new Parameter[] { AutowiredParmeter }, out var propertyValue)) { return(propertyValue); } } } else { var instanceTypeParameter = new AutowiredParmeter(); // ReSharper disable once PossibleNullReferenceException instanceTypeParameter.TryAdd(getAutowiredParmeterKey(property.DeclaringType), instance); if (context.TryResolveService(propertyService, new Parameter[] { instanceTypeParameter }, out var propertyValue)) { return(propertyValue); } } return(null); }
public RepositoryRegistrationBuilder <TRoot, TId> ImplementsSave() { _implementations["save"] = new KeyedService(RepositoryRegistrationKeys.Save, typeof(ISave <TRoot, TId>)); return(this); }
/// <summary> /// Gets data about a service implementation. /// </summary> /// <param name="value"> /// The constructor string passed in to the service host factory /// that is used to determine which type to host/use as a service /// implementation. /// </param> /// <returns> /// A <see cref="Autofac.Integration.Wcf.ServiceImplementationData"/> /// object containing information about which type to use in /// the service host and which type to use to resolve the implementation. /// </returns> /// <remarks> /// <para> /// This resolver takes the constructor string stored in the .svc file /// and resolves a matching keyed or typed service from the root /// application container. That resolved type is used both for the /// service host as well as the implementation type. /// </para> /// </remarks> /// <exception cref="System.InvalidOperationException"> /// Thrown if the <see cref="Autofac.Integration.Wcf.AutofacHostFactory.Container"/> /// is <see langword="null" />; /// if the service indicated by <paramref name="value" /> /// is not registered with the <see cref="Autofac.Integration.Wcf.AutofacHostFactory.Container"/>; /// or if the service is a singleton that isn't registered as a singleton. /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="value" /> is <see langword="null" />. /// </exception> /// <exception cref="System.ArgumentException"> /// Thrown if <paramref name="value" /> is empty. /// </exception> public virtual ServiceImplementationData GetServiceImplementationData(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length == 0) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Properties.Resources.ArgumentException_StringEmpty, "value")); } if (AutofacHostFactory.Container == null) { throw new InvalidOperationException(AutofacHostFactoryResources.ContainerIsNull); } Service serviceBeingResolved = new KeyedService(value, typeof(object)); IComponentRegistration registration = null; if (!AutofacHostFactory.Container.ComponentRegistry.TryGetRegistration(serviceBeingResolved, out registration)) { Type serviceType = Type.GetType(value, false); if (serviceType != null) { serviceBeingResolved = new TypedService(serviceType); AutofacHostFactory.Container.ComponentRegistry.TryGetRegistration(serviceBeingResolved, out registration); } } if (registration == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AutofacHostFactoryResources.ServiceNotRegistered, value)); } var data = new ServiceImplementationData { ConstructorString = value, ServiceTypeToHost = registration.Activator.LimitType, ImplementationResolver = l => l.ResolveComponent(new ResolveRequest(serviceBeingResolved, registration, Enumerable.Empty <Parameter>())) }; var implementationType = registration.Activator.LimitType; if (IsSingletonWcfService(implementationType)) { if (!IsRegistrationSingleInstance(registration)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AutofacHostFactoryResources.ServiceMustBeSingleInstance, implementationType.FullName)); } data.HostAsSingleton = true; } else { if (IsRegistrationSingleInstance(registration)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, AutofacHostFactoryResources.ServiceMustNotBeSingleInstance, implementationType.FullName)); } } return(data); }
public RepositoryRegistrationBuilder <TRoot, TId> ImplementsDelete() { _implementations["delete"] = new KeyedService(RepositoryRegistrationKeys.Delete, typeof(IDelete <TRoot, TId>)); return(this); }
public RepositoryRegistrationBuilder <TRoot, TId> WithCachedRead(string key = RepositoryRegistrationKeys.CachedRead) { _implementations["read"] = new KeyedService(key, typeof(IRead <TRoot, TId>)); return(this); }
/// <summary>Resolves the service</summary> public static object ResolveService(this IComponentContext context, KeyedService ks) => context.Container.Resolve(ks.ServiceType, ks.ServiceKey);