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


C# IContainer.BeginLifetimeScope方法代码示例

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


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

示例1: Init

        public void Init() {
            _settingsA = new ShellSettings { Name = "Alpha" };
            _settingsB = new ShellSettings { Name = "Beta", };
            _routes = new RouteCollection();

            var rootBuilder = new ContainerBuilder();
            rootBuilder.Register(ctx => _routes);
            rootBuilder.RegisterType<ShellRoute>().InstancePerDependency();
            rootBuilder.RegisterType<RunningShellTable>().As<IRunningShellTable>().SingleInstance();
            rootBuilder.RegisterModule(new WorkContextModule());
            rootBuilder.RegisterType<WorkContextAccessor>().As<IWorkContextAccessor>().InstancePerMatchingLifetimeScope("shell");
            rootBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
            rootBuilder.RegisterType<ExtensionManager>().As<IExtensionManager>();
            rootBuilder.RegisterType<StubCacheManager>().As<ICacheManager>();
            rootBuilder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
            rootBuilder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();

            _rootContainer = rootBuilder.Build();

            _containerA = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsA);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });

            _containerB = _rootContainer.BeginLifetimeScope(
                "shell",
                builder => {
                    builder.Register(ctx => _settingsB);
                    builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
                });
        }
开发者ID:dioptre,项目名称:nkd,代码行数:33,代码来源:ShellRouteTests.cs

示例2: FactBase

        public FactBase(ITestOutputHelper outputHelper)
        {
            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterModule(new PosAppModule());
            m_container = containerBuilder.Build();
            m_testScope = m_container.BeginLifetimeScope();

            DatabaseHelper.ResetDatabase();
            m_outputRedirector = new OutputRedirector(outputHelper);

            Fixtures = new Fixtures(m_container.BeginLifetimeScope());
        }
开发者ID:XiaoVLiu,项目名称:PosApp-PWC,代码行数:12,代码来源:FactBase.cs

示例3: LifetimeScopeCheck

 static void LifetimeScopeCheck(IContainer container)
 {
     int previousScopeComponentHashcode;
       using (ILifetimeScope scopeContext = container.BeginLifetimeScope())
       {
     Debug.Assert(scopeContext.Resolve<Movie>().GetHashCode() == scopeContext.Resolve<Movie>().GetHashCode());
     previousScopeComponentHashcode = scopeContext.Resolve<Movie>().GetHashCode();
       }
       using (ILifetimeScope scopeContext = container.BeginLifetimeScope())
       {
     Debug.Assert(scopeContext.Resolve<Movie>().GetHashCode() != previousScopeComponentHashcode);
       }
 }
开发者ID:piotrcierpich,项目名称:DiAutofac,代码行数:13,代码来源:ScopingExample.cs

示例4: Application_Start

        protected void Application_Start()
        {
            SessionScope.SetSessionScopeService(new WebSessionScopeService());
            RequestScope.SetRequestScopeService(new WebRequestScopeService());

            var builder = new ContainerBuilder();

            builder.RegisterModule<ServiceModule>();
            builder.RegisterModule<DomainModule>();
            builder.RegisterModule<QueryModelModule>();

            builder.Register(a => new AutofacDependencyResolver(() => CurrentLifetimeScope, DependencyResolver.Current))
                   .As<IDependencyResolver>()
                   .SingleInstance();

            builder.RegisterType<AutofacControllerFactory>().As<IControllerFactory>().SingleInstance();

            builder.RegisterType<DotLessCompiler>().AsSelf().SingleInstance();

            RegisterComponents(builder);

            _container = builder.Build();

            CurrentLifetimeScope = _container.BeginLifetimeScope();

            DependencyResolver.SetResolver(_container.Resolve<IDependencyResolver>());

            RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            RouteTable.Routes.MapRoute("Login", "login", new { controller = "account", action = "login" });

            RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
                                       new {controller = "Dashboard", action = "Index",
                                       id = UrlParameter.Optional});
        }
开发者ID:wingertge,项目名称:test,代码行数:35,代码来源:Application.cs

示例5: Init

        public void Init() {
            var builder = new ContainerBuilder();
            builder.RegisterType<DefaultProcessingEngine>().As<IProcessingEngine>();
            builder.RegisterModule(new WorkContextModule());
            builder.RegisterType<WorkContextAccessor>().As<IWorkContextAccessor>();
            builder.RegisterAutoMocking(MockBehavior.Loose);
            _container = builder.Build();

            _shellContext = new ShellContext {
                Descriptor = new ShellDescriptor(),
                Settings = new ShellSettings(),
                LifetimeScope = _container.BeginLifetimeScope(),
            };

            var httpContext = new StubHttpContext();

            _container.Mock<IShellContextFactory>()
                .Setup(x => x.CreateDescribedContext(_shellContext.Settings, _shellContext.Descriptor))
                .Returns(_shellContext);
            _container.Mock<IHttpContextAccessor>()
                .Setup(x=>x.Current())
                .Returns(httpContext);
            _container.Mock<IHttpContextAccessor>()
                .Setup(x => x.CreateContext(It.IsAny<ILifetimeScope>()))
                .Returns(httpContext);

        }
开发者ID:killgitbug,项目名称:Orchard,代码行数:27,代码来源:DefaultProcessingEngineTests.cs

示例6: WithAutofac

        /// <summary>
        /// Configures a <see cref="NDomain.IoC.IDependencyResolver"/> to use Autofac 
        /// based on the <paramref name="container"/>. Useful to resolve application message handlers
        /// that depend on other components external to NDomain.
        /// The application's Autofac container will also get updated with registries for NDomain's components.
        /// </summary>
        /// <param name="b">configurator instance</param>
        /// <param name="container">application's Autofac container</param>
        /// <returns>Current configurator instance, to be used in a fluent manner.</returns>
        public static IoCConfigurator WithAutofac(this IoCConfigurator b, IContainer container)
        {
            b.Resolver = new AutofacDependencyResolver(container.BeginLifetimeScope());

            b.Configured += context =>
            {
                var builder = new ContainerBuilder();
                builder.RegisterInstance(context);

                builder.RegisterInstance(context.CommandBus);
                builder.RegisterInstance(context.EventBus);
                builder.RegisterInstance(context.EventStore).As<IEventStore>();
                builder.RegisterGeneric(typeof(AggregateRepository<>))
                       .As(typeof(IAggregateRepository<>)).SingleInstance();

                // usually command/event handlers
                foreach (var knownType in b.KnownTypes)
                {
                    builder.RegisterType(knownType)
                           .AsSelf()
                           .PreserveExistingDefaults();
                }

                builder.Update(container);
            };

            return b;
        }
开发者ID:mfelicio,项目名称:NDomain,代码行数:37,代码来源:AutofacConfigurator.cs

示例7: InitializeAndRunApplication

 private static RecordsProcessedResult InitializeAndRunApplication(string[] args, IContainer builder)
 {
     RecordsProcessedResult result;
     using (var scope = builder.BeginLifetimeScope())
     {
         var processor = scope.Resolve<IRecordProcessor>();
         result = processor.Run(args);
     }
     return result;
 }
开发者ID:RyanFerretti,项目名称:RecordProcessor,代码行数:10,代码来源:Program.cs

示例8: GetLifetimeScope

 public static ILifetimeScope GetLifetimeScope(IContainer container)
 {
     if (IsValid())
     {
         if (null == lifetimeScope)
             lifetimeScope = container.BeginLifetimeScope(tag);
         return lifetimeScope;
     }
     else
         return null;
 }
开发者ID:popunit,项目名称:MyEFramework,代码行数:11,代码来源:AutofacLifetimeScopeHttpModule.cs

示例9: Main

		static void Main(string[] args)
		{
			Container = AutofacConfig.Configure();

            Console.WriteLine("Welcome to Hue!");

            using (var scope = Container.BeginLifetimeScope())
            {
                var consoleModeRunner = new ConsoleModeRunner(scope, Console.Out, Console.In);
                consoleModeRunner.Run();
            }
        }
开发者ID:jchurchill,项目名称:hue,代码行数:12,代码来源:Program.cs

示例10: LoadCaches

        /// <summary>
        /// Loads any caches.
        /// </summary>
        /// <param name="container">
        /// The Autofac container. Needed to resolve the searcher.
        /// </param>
        public static void LoadCaches(IContainer container)
        {
            // Creating these scopes on the fly is not nice.
            // But we do want to load the suggestions caches at application startup, so doesn't seem to be much choice.

            using (var scope = container.BeginLifetimeScope())
            {
                var constants = scope.Resolve<IConstants>();

                var searcher = scope.Resolve<IProductSearcher>();
                searcher.LoadProductStore(constants.AbsoluteLucenePath, constants.ProductCodeBoost, constants.MinSimilarity, true);
            }
        }
开发者ID:stephengodbold,项目名称:searchpdproj,代码行数:19,代码来源:SearcherConfig.cs

示例11: Main

        static void Main(string[] args)
        {
            string teamName = "FlyingBirds", password = "mypassword";

            if (args.Count() == 2)
            {
                teamName = args[0].Trim();
                password = args[1].Trim();
            }

            Console.Title = teamName;
            Console.BackgroundColor = ConsoleColor.White;
            Console.Clear();

            var builder = new ContainerBuilder();

            //Authenticator
            builder.RegisterType<HttpBasicAuthenticator>().As<IAuthenticator>().WithParameters(new Autofac.Core.Parameter[]
            {
                new NamedParameter("username", teamName),
                new NamedParameter("password", password)
            });
            //Rest client
            builder.RegisterType<RestClient>().As<IRestClient>()
                .UsingConstructor(typeof(string)).WithParameters(new Autofac.Core.Parameter[]
            {
                new NamedParameter("baseUrl", ConfigurationManager.AppSettings["ServerBaseAddress"])
            });
            //IO
            builder.RegisterType<Writer>().As<IWriter>().WithParameters(new Autofac.Core.Parameter[]
            {
                new NamedParameter("teamName", teamName)
            });
            //Player
            builder.RegisterType<Player>().As<IPlayer>().WithParameters(new Autofac.Core.Parameter[]
            {
                new NamedParameter("myTeamName", teamName)
            });
            //Algo
            builder.RegisterType<CardStrategy>().As<ICardStrategy>();

            Container = builder.Build();

            using (var scope = Container.BeginLifetimeScope())
            {
                var player = scope.Resolve<IPlayer>();

                player.Play();
            }
        }
开发者ID:makinggoodsoftware,项目名称:rbs_challenge_nov,代码行数:50,代码来源:Program.cs

示例12: UseAutofacMiddleware

        public static IAppBuilder UseAutofacMiddleware(this IAppBuilder app, IContainer container)
        {
            app.Use(async (context, next) =>
            {
                using (var lifetimeScope = container.BeginLifetimeScope(Constants.LifetimeScopeTag,
                    b => b.RegisterInstance(context).As<IOwinContext>()))
                {
                    context.Set(Constants.OwinLifetimeScopeKey, lifetimeScope);
                    await next();
                }
            });

            return UseMiddlewareFromContainer(app, container);
        }
开发者ID:yuleyule66,项目名称:autofac,代码行数:14,代码来源:OwinExtensions.cs

示例13: SelectData

        static void SelectData()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<DatabaseManager>();
            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));

            Container = builder.Build();

            using (var scope = Container.BeginLifetimeScope())
            {
                var manager = scope.Resolve<DatabaseManager>();
                manager.Search("SELECT * FORM USER");
            }
        }
开发者ID:jovijovi,项目名称:kort,代码行数:14,代码来源:Run.cs

示例14: BuildContainer

        public static void BuildContainer()
        {
            var builder = new ContainerBuilder();
            ConfigureAndRegisterUserIdentityModule(builder);

            ConfigureAndRegisterDataModule(builder);
            ConfigureAndRegisterControllers(builder);
            RegisterModules(builder);

            Container = builder.Build();
            SetSpecificationScopeProvider();
            InitialiseDatabaseAndWebSecurity();
            Container.InitialiseAutoMapper(Container.BeginLifetimeScope().Resolve);
        }
开发者ID:Gwayaboy,项目名称:MVCSolutionSample,代码行数:14,代码来源:TestConfigurator.cs

示例15: Main

        static void Main()
        {
            var builder = new ContainerBuilder();

            //builder.RegisterType<ConsoleOutput>().As<IOutput>();
            //builder.RegisterType<TodayWriter>().As<IDateWriter>();
            //builder.RegisterType<DateWriter>();

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsSelf().AsImplementedInterfaces();

            Container = builder.Build();

            using (var scope = Container.BeginLifetimeScope())
            {
                var dateWriter = new DateWriter(scope.Resolve<IDateWriter>());
                dateWriter.Write();
            }

            using (var scope = Container.BeginLifetimeScope())
            {
                var dateWriter = scope.Resolve<DateWriter>();
                dateWriter.Write();
            }
        }
开发者ID:joenjuki,项目名称:design-patterns,代码行数:24,代码来源:Program.cs


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