当前位置: 首页>>代码示例>>C#>>正文


C# ContainerBuilder.RegisterGenericDecorator方法代码示例

本文整理汇总了C#中Autofac.ContainerBuilder.RegisterGenericDecorator方法的典型用法代码示例。如果您正苦于以下问题:C# ContainerBuilder.RegisterGenericDecorator方法的具体用法?C# ContainerBuilder.RegisterGenericDecorator怎么用?C# ContainerBuilder.RegisterGenericDecorator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Autofac.ContainerBuilder的用法示例。


在下文中一共展示了ContainerBuilder.RegisterGenericDecorator方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BuildContainer

        private static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<Database>().As<IDatabase>().InstancePerLifetimeScope();
            builder.RegisterType<ConsoleLogger>().As<ILogger>().InstancePerLifetimeScope();

            // Register the mediator
            builder.Register(c => new Mediator(c.Resolve<IComponentContext>().Resolve))
                .AsImplementedInterfaces()
                .SingleInstance();

            // Register all IValidator<T>
            builder.RegisterAssemblyTypes(typeof (Program).Assembly)
                .AsClosedTypesOf(typeof (IValidator<>))
                .InstancePerLifetimeScope();

            // Register all ICommandHandler<TCommand, TResult>
            builder.RegisterAssemblyTypes(typeof (Program).Assembly)
                .AsClosedTypesOf(typeof (ICommandHandler<,>), "handler")
                .InstancePerLifetimeScope();

            // Decorate command handlers with validation
            builder.RegisterGenericDecorator(
                typeof(ValidationCommandHandler<,>),
                typeof(ICommandHandler<,>), "handler", "validation");

            // Decorate validation command handlers with timing
            builder.RegisterGenericDecorator(
                typeof (TimingCommandHandler<,>),
                typeof (ICommandHandler<,>), "validation");

            return builder.Build();
        }
开发者ID:khellang,项目名称:CommandHandlerExample,代码行数:34,代码来源:Program.cs

示例2: ConfigureServices

        // This method gets called by a runtime.
        // Use this method to add services to the container
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var builder = new ContainerBuilder();

            builder.RegisterType<ConcreteCacheProvider>().As<ICacheProvider>();
            builder.RegisterType<SerilogLoggerFactory>().As<ILoggerFactory>();

            builder.RegisterType(typeof(ThingyRepository)).Named<IRepository<Thingy>>("repository");

            builder.RegisterGenericDecorator(
                    typeof(CachedRepository<>),
                    typeof(IRepository<>),
                    fromKey: "repository")
                    .Keyed("decorated", typeof(IRepository<>));

            builder.RegisterGenericDecorator(
                    typeof(PerformanceLoggingRepository<>),
                    typeof(IRepository<>),
                    fromKey: "decorated");

            builder.Populate(services);

            var container = builder.Build();

            return container.ResolveOptional<IServiceProvider>();
        }
开发者ID:Stavrakakis,项目名称:Patterns,代码行数:30,代码来源:Startup.cs

示例3: Main

        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            var executingAssembly = Assembly.GetExecutingAssembly();
            //for debugging only
            var tasks = executingAssembly.GetTypes().Where(t => t.Name.EndsWith("Task", StringComparison.Ordinal)).ToList();
            builder.RegisterAssemblyTypes(executingAssembly)
                .As(type => type.GetInterfaces()
                .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof (IRequestHandler<, >)))
                .Select(interfaceType => new KeyedService("requestHandler", interfaceType))); // --> we need a keyed service as the decorated service will become the key-less one

            //register the decorator - works
            builder.RegisterGenericDecorator(typeof (LogHandler<, >), typeof (IRequestHandler<, >), "requestHandler", "decoratedWithLog");
            builder.RegisterGenericDecorator(typeof (TransactionHandler<, >), typeof (IRequestHandler<, >), "decoratedWithLog"); //double logged! ->key-less
            var container = builder.Build();

            //get the original undecorated handler by using key
            var commandUndec = container.ResolveKeyed<IRequestHandler<TestRequest, Unit>>("requestHandler");
            commandUndec.Handle(new TestRequest{Title = "undecorated"});
            Console.WriteLine();

            //get the decorated one
            var command = container.Resolve<IRequestHandler<TestRequest, Unit>>();
            command.Handle(new TestRequest{Title = "decorated"});
            Console.WriteLine();

            //finally, use the mediator to resolve everything for us
            var _mediator = new Mediator(container);
            _mediator.Send(new TestRequest{Title = "Test"});
            Console.ReadLine();
        }
开发者ID:jodegreef,项目名称:DecoratedRequestHandlers,代码行数:31,代码来源:Program.cs

示例4: Create

        public static IContainer Create(Action<ContainerBuilder> additionalRegistrations)
        {
            IContainer container = null;

            var builder = new ContainerBuilder();

            //Command handlers
            var featuresAssembly = typeof(Features.Features).Assembly;
            builder.RegisterAssemblyTypes(featuresAssembly)
                .As(type => type.GetInterfaces()
                .Where(interfaceType => !interfaceType.Namespace.Contains("Decorators") && interfaceType.IsClosedTypeOf(typeof(IRequestHandler<,>)))
                .Select(interfaceType => new KeyedService("requestHandler", interfaceType))); // --> we need a keyed service as the decorated service will become the key-less one

            //query handlers
            builder.RegisterAssemblyTypes(typeof(GetCompleteInventoryQueryHandler).Assembly)
                .Where(interfaceType => !interfaceType.Namespace.Contains("Decorators") && interfaceType.IsClosedTypeOf(typeof(IRequestHandler<,>)))
                .AsImplementedInterfaces();

            //builder.Register(c => new Mediator(c.Resolve<IComponentContext>())).AsImplementedInterfaces();
            builder.RegisterSource(new ContravariantRegistrationSource());
            builder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces();
            builder.Register<SingleInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });
            builder.Register<MultiInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
            });

            builder.RegisterType<UnitOfWork>().AsImplementedInterfaces();
            builder.Register<IQueryContext>(c => new QueryContext(new BookKeepingContext()));

            builder.Register<IUnitOfWork>(c => new UnitOfWork(new BookKeepingContext())).SingleInstance();

            builder.RegisterType<LegoSetRepository>().AsImplementedInterfaces();
            //builder.RegisterType<InMemLegoSetRepository>().AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(featuresAssembly)
               .Where(t => t.Name.EndsWith("Validator"))
               .AsImplementedInterfaces();

            //register the decorator - works
            builder.RegisterGenericDecorator(typeof(ValidationHandler<,>), typeof(IRequestHandler<,>), "requestHandler", "decoratedWithValidation");
            builder.RegisterGenericDecorator(typeof(LogHandler<,>), typeof(IRequestHandler<,>), "decoratedWithValidation", "decoratedWithLog");
            builder.RegisterGenericDecorator(typeof(UnitOfWorkHandler<,>), typeof(IRequestHandler<,>), "decoratedWithLog"); //last decorator must be keyless

            if (additionalRegistrations != null)
                additionalRegistrations.Invoke(builder);

            container = builder.Build();

            return container;
        }
开发者ID:jodegreef,项目名称:BookKeeping45,代码行数:56,代码来源:Bootstrap.cs

示例5: Load

        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

              var nancyAssembly = typeof(AppModule).Assembly;

              // Register validators
              builder.RegisterAssemblyTypes(nancyAssembly)
             .AsClosedTypesOf(typeof(IValidator<>))
             .SingleInstance();

              // register all query handlers
              builder.RegisterAssemblyTypes(nancyAssembly)
             .Where(t => t.IsClosedTypeOf(typeof(IHandler<>)))
             .AsImplementedInterfaces();
              builder.RegisterAssemblyTypes(nancyAssembly)
             .Where(t => t.IsClosedTypeOf(typeof(IHandler<,>)))
             .As(t => new KeyedService("queryHandler", t.GetInterfaces().Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandler<,>))));
              builder.RegisterGenericDecorator(typeof(RequestValidationAwareHandler<,>), typeof(IHandler<,>), "queryHandler");

              // Register other stuff
              builder.RegisterType<NancyIdentityFromContextAssigner>()
             .AsImplementedInterfaces()
             .SingleInstance();
              builder.RegisterType<NancySecurityContextFactory>()
             .AsImplementedInterfaces()
             .SingleInstance();
        }
开发者ID:DavidLievrouw,项目名称:InvoiceGen,代码行数:28,代码来源:NancyModule.cs

示例6: Load

        protected override void Load(ContainerBuilder builder)
        {
            var assemblies = GetAssemblies();

            //register mediator
            builder.RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            //register request handlers
            builder.RegisterAssemblyTypes(assemblies)
                .Where(type => type.IsClosedTypeOf(typeof(IRequestHandler<,>)))
                .As(type => new KeyedService("handler", GetGenericType(type)))
                .InstancePerLifetimeScope();

            //register request validators
            builder.RegisterAssemblyTypes(assemblies)
                .AsClosedTypesOf(typeof(IValidator<>))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();

            //register validation decorator
            builder.RegisterGenericDecorator(
                typeof(ValidationRequestHandler<,>),
                typeof(IRequestHandler<,>),
                fromKey: "handler",
                toKey: "requestPipeline")
                .InstancePerLifetimeScope();
        }
开发者ID:Firebuild,项目名称:Firebuild,代码行数:29,代码来源:MediatorPipeline.cs

示例7: Load

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(typeof(Repository<>).Assembly)
                .AsClosedTypesOf(typeof(IRepository<>))
                .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(ICommandHandler<,>).Assembly)
                //.AsClosedTypesOf(typeof(ICommandHandler<,>))
                //.Named("implementor", typeof(ICommandHandler<,>))
                .As(t => t.GetInterfaces()
                  .Where(i => i.IsClosedTypeOf(typeof(ICommandHandler<,>)))
                  .Select(i => new KeyedService("commandImplementor", i))
                  .Cast<Service>())
                .InstancePerLifetimeScope();

            builder.RegisterGenericDecorator(
                typeof(TransactionalCommandHandler<,>),
                typeof(ICommandHandler<,>), fromKey: "commandImplementor");

            builder.RegisterAssemblyTypes(typeof(IQueryHandler<,>).Assembly)
                .AsClosedTypesOf(typeof(IQueryHandler<,>))
                .InstancePerLifetimeScope();

            builder.RegisterType<AuthorizationServerProvider>()
                .AsSelf();

            builder.RegisterType<ApplicationDbContext>()
                .AsImplementedInterfaces()
                .AsSelf()
                .InstancePerLifetimeScope();

            builder.RegisterType<StubCryptoStore>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterType<GcmEncryptionAlgorithm>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterType<HmacSha512HashAlgorithm>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterType<NullUserBasedDataProtection>()
                .AsImplementedInterfaces()
                .SingleInstance();

            builder.RegisterType<CryptoService>()
                .AsImplementedInterfaces()
                .SingleInstance();
        }
开发者ID:Lsuwito,项目名称:SampleApp,代码行数:51,代码来源:ApplicationModule.cs

示例8: RegisterHandlers

        private static void RegisterHandlers(ContainerBuilder builder)
        {
            builder.RegisterType<Mediator>()
                .As<IMediator>();

            builder.RegisterAssemblyTypes(typeof(Mediator).Assembly)
                .As(type => type.GetInterfaces()
                    .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(IRequestHandler<,>)))
                    .Select(interfaceType => new KeyedService("handler", interfaceType)));

            builder.RegisterGenericDecorator(
                typeof(LoggingHandlerDecorator<,>),
                typeof(IRequestHandler<,>),
                fromKey: "handler");
        }
开发者ID:ddraganov,项目名称:FMI-WebDev2015,代码行数:15,代码来源:Global.asax.cs

示例9: GetRegistrations

        public ContainerBuilder GetRegistrations()
        {
            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            //Security
            builder.Register<ISecurityPoint>(_ => new DefaultSecurityPoint()).SingleInstance();

            //  Data & Co.
            builder.Register(_ => new UnitOfWork(_.Resolve<ThingDbContext>()))
                .InstancePerLifetimeScope().AsImplementedInterfaces();

            builder.Register(_ => new ThingRepository(_.Resolve<ThingDbContext>()))
                .InstancePerLifetimeScope().AsImplementedInterfaces();

            builder.RegisterType<ThingDbContext>()
                .AsSelf().InstancePerLifetimeScope();

            //  Validators
            RegisterValidators(builder);

            //  MediatR
            builder.RegisterSource(new ContravariantRegistrationSource());
            builder.RegisterAssemblyTypes(typeof (IMediator).Assembly)
                .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof (ThingCommand).Assembly)
                .As(o => o.GetInterfaces()
                    .Where(i => i.IsClosedTypeOf(typeof (IAsyncRequestHandler<,>)))
                    .Select(i => new KeyedService("async-handlers", i)));
            builder.Register<SingleInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });
            builder.Register<MultiInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => (IEnumerable<object>) c.Resolve(typeof (IEnumerable<>).MakeGenericType(t));
            });
            builder.RegisterGenericDecorator(typeof (AsyncValidationRequestHandler<,>), typeof (IAsyncRequestHandler<,>),
                "async-handlers"); // The outermost decorator should not have a toKey

            return builder;
        }
开发者ID:lucamilan,项目名称:CleanAndTestable,代码行数:45,代码来源:CompositionRoot.cs

示例10: Load

        protected override void Load(ContainerBuilder builder)
        {
            //TODO: clean this up scanning the assembly multiple times is prolly not a good idea.

            builder.RegisterSource(new ContravariantRegistrationSource());

            builder.RegisterAssemblyTypes(typeof(IMediator).Assembly)
                .AsImplementedInterfaces();

            builder.Register<SingleInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });
            builder.Register<MultiInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve<IComponentContext>();
                return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
            });

            //register all notification handlers
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .As(type => type.GetInterfaces()
                    .Where(interfacetype => interfacetype.IsClosedTypeOf(typeof(IAsyncNotificationHandler<>))));

            //register all pre handlers
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .As(type => type.GetInterfaces()
                    .Where(interfacetype => interfacetype.IsClosedTypeOf(typeof(IAsyncPreRequestHandler<>))));

            //register all post handlers
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .As(type => type.GetInterfaces()
                    .Where(interfacetype => interfacetype.IsClosedTypeOf(typeof(IAsyncPostRequestHandler<,>))));

            //register all handlers
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
               .As(type => type.GetInterfaces()
                   .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof(IAsyncRequestHandler<,>)))
                   .Select(interfaceType => new KeyedService("asyncRequestHandler", interfaceType)));

            //register pipeline decorators
            builder.RegisterGenericDecorator(typeof(AsyncMediatorPipeline<,>), typeof(IAsyncRequestHandler<,>), "asyncRequestHandler");
        }
开发者ID:NotMyself,项目名称:App,代码行数:44,代码来源:MediatorModule.cs

示例11: RegisterContentParts

        private static void RegisterContentParts(IAppBuilder app, ContainerBuilder builder)
        {
            string encryptionKey = "dn18fj!dhA)mp";

            builder.RegisterType<NLogLogger>().As<ICommonLogger>();
            builder.RegisterType<AspNetCacheProvider>().As<ICacheProvider>();
            builder.RegisterInstance(new ContentEncryption(encryptionKey)).As<IContentEncryption>();
            builder.RegisterType<NoCaptchaProvider>().As<ICaptchaProvider>();
            builder.RegisterType<CommentStateProvider>().As<ICommentStateProvider>();

            builder.RegisterInstance(ESSettings.FromConfig()).AsSelf();
            builder.RegisterType<ESObjectIdQueries>().As<ISearchQueries<ObjectId>>();

            builder.RegisterInstance(MongoDbConnectionSettings.FromConfig()).AsSelf();
            builder.RegisterType<MongoDbContentQueries>().Named<IContentQueries<ObjectId>>("data");
            builder.RegisterType<MongoDbCommentQueries>().Named<ICommentQueries<ObjectId>>("data");
            builder.RegisterType<MongoDbCategoryQueries>().Named<ICategoryQueries<ObjectId>>("data");

            builder.RegisterGenericDecorator(
                typeof(SingleInstancePostCache<>), typeof(IContentQueries<>), fromKey: "data");
            builder.RegisterGenericDecorator(
                typeof(SingleInstanceCommentCache<>), typeof(ICommentQueries<>), fromKey: "data");
            builder.RegisterGenericDecorator(
                typeof(SingleInstanceCategoryCache<>), typeof(ICategoryQueries<>), fromKey: "data");

            builder.RegisterType<CategoryManager<ObjectId>>().As<ICategoryManager<ObjectId>>();
            builder.RegisterType<CommentManager<ObjectId>>().As<ICommentManager<ObjectId>>().InstancePerRequest();
            builder.RegisterType<CustomContentManager>().AsSelf().InstancePerRequest();
        }
开发者ID:RodionKulin,项目名称:ContentManagementBackend,代码行数:29,代码来源:AutofacConfig.cs

示例12: DecorateHandlers

        private static void DecorateHandlers(ContainerBuilder builder)
        {
            builder.RegisterGenericDecorator(
                typeof(ValidationRequestHandler<,>),
                typeof(IRequestHandler<,>),
                fromKey: "handler1",
                toKey: "handler2")
                .InstancePerMatchingLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);

            builder.RegisterGenericDecorator(
                typeof(LogRequestHandler<,>),
                typeof(IRequestHandler<,>),
                fromKey: "handler2",
                toKey: Consts.RequestPipelineKey)
                .InstancePerMatchingLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
        }
开发者ID:Firebuild,项目名称:Firebuild,代码行数:16,代码来源:Bootstrapper.cs


注:本文中的Autofac.ContainerBuilder.RegisterGenericDecorator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。