public static void RegisterWithContext <TService>(this Container container, Func <DependencyContext, TService> contextBasedFactory) where TService : class { if (contextBasedFactory == null) { throw new ArgumentNullException("contextBasedFactory"); } Func <TService> rootFactory = () => contextBasedFactory(DependencyContext.Root); // Should always be transient! container.Register <TService>(rootFactory, Lifestyle.Transient); // Allow the Func<DependencyContext, TService> to be injected into parent types. container.ExpressionBuilding += (sender, e) => { if (e.RegisteredServiceType != typeof(TService)) { var rewriter = new DependencyContextRewriter { ServiceType = e.RegisteredServiceType, ContextBasedFactory = contextBasedFactory, RootFactory = rootFactory, Expression = e.Expression }; e.Expression = rewriter.Visit(e.Expression); } }; }
/// <summary> /// Registers with a context. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="container">The container.</param> /// <param name="contextBasedFactory">The context based factory.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="contextBasedFactory"/> is <see langword="null"/>. /// </exception> public static void RegisterWithContext <TService>( this Container container, Func <DependencyContext, TService> contextBasedFactory) where TService : class { contextBasedFactory.AssertNotNull("contextBasedFactory"); Func <TService> rootFactory = () => { return(contextBasedFactory(DependencyContext.Root)); }; container.Register <TService>(rootFactory, Lifestyle.Transient); // Allow the Func<DependencyContext, TService> to be // injected into parent types. container.ExpressionBuilding += (sender, e) => { if (e.RegisteredServiceType != typeof(TService)) { var rewriter = new DependencyContextRewriter { ServiceType = e.RegisteredServiceType, ContextBasedFactory = contextBasedFactory, RootFactory = rootFactory, Expression = e.Expression }; e.Expression = rewriter.Visit(e.Expression); } }; }