Exemplo n.º 1
0
 public void Register(Container container)
 {
     container.RegisterSingle<IMapper, Mapper>();
     container.RegisterSingle<IConnectionStringProvider, ConnectionStringProvider>();
     container.RegisterSingle<IDbConnectionProvider, SqlConnectionProvider>();
     container.RegisterSingle<IEmailSender, EmailSender>();
 }
Exemplo n.º 2
0
Arquivo: App.cs Projeto: NamXH/Orchard
 static App()
 {
     Container = new Container();
     Container.RegisterSingle(() => new Step1VM());
     Container.RegisterSingle(() => new Step2VM());
     Container.RegisterSingle(() => new Step3VM());
     Container.RegisterSingle(() => new Step4VM());
 }
Exemplo n.º 3
0
        public void RegisterServices(Container container) {
            container.Options.AllowOverridingRegistrations = true;
            container.RegisterPackage<Core.Bootstrapper>();

            container.RegisterSingle<IMembershipSecurity, DefaultMembershipSecurity>();
            container.RegisterSingle<IMembershipProvider, MembershipProvider>();

            if (Settings.Current.EnableJobsModule)
                DynamicModuleUtility.RegisterModule(typeof(ExceptionlessJobHttpModule));
        }
Exemplo n.º 4
0
        public static void Initialize()
        {
            // Create the container as usual.
            var container = new Container();

            //setup logger
            container.RegisterSingle<ILogger>(() =>
                new LoggerConfiguration()
                .WriteTo.ColoredConsole()
                .WriteTo.Trace()
                .CreateLogger()
            );
            
            //instagram config for InstaSharp
            container.RegisterSingle<InstagramConfig>(() =>
            {
                var clientId = ConfigurationManager.AppSettings["clientId"];
                var clientSecret = ConfigurationManager.AppSettings["clientSecret"];
                var callbackUri = ConfigurationManager.AppSettings["callbackUri"];
                var redirectUri = ConfigurationManager.AppSettings["redirectUri"];

                var icfg = new InstagramConfig(clientId, clientSecret);
                icfg.CallbackUri = callbackUri;
                icfg.RedirectUri = redirectUri;
                return icfg;
            }
            );

            // Azure storage account
            container.RegisterSingle(() =>
            {
                var connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
                return CloudStorageAccount.Parse(connectionString);
            });

            // Azure table client
            container.RegisterSingle(() => container.GetInstance<CloudStorageAccount>().CreateCloudTableClient());

            //register our tablesets, in this case we only have one
            container.RegisterWebApiRequest<ITableSet<RealtimeSubscription>>(() =>
                new TableSet<RealtimeSubscription>(container.GetInstance<CloudTableClient>())
                );

            //register repositories
            container.Register<ISubscriptionRepository, SubscriptionRepository>(Lifestyle.Singleton);

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }
Exemplo n.º 5
0
        private void InjectDependencies(HttpConfiguration config)
        {
            var container = new Container();

            container.RegisterSingle(() => ChecklistRepository);
            container.RegisterSingle(() => ControllerConfiguration);

            container.RegisterWebApiControllers(config);
            container.Verify();

            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Exemplo n.º 6
0
        private void InjectDependencies(HttpConfiguration config)
        {
            var container = new Container();

            container.RegisterSingle<IChecklistRepository>(() => new ChecklistRepository(RepositoryConnectionString, DatabaseName));
            container.RegisterSingle<IControllerConfiguration>(() => new ControllerConfiguration {PageSizeLimit = MaximumPageSize});

            container.RegisterWebApiControllers(config);
            container.Verify();

            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Exemplo n.º 7
0
 public void Register(Container container)
 {
     container.RegisterSingle(() =>
     {
         var rabbitMqHost = ConfigurationManager.AppSettings["RabbitMQHost"];
         if (string.IsNullOrEmpty(rabbitMqHost)) throw new Exception("You must provide a 'RabbitMQHost' app setting.");
         return RabbitHutch.CreateBus("host=" + rabbitMqHost);
     });
     container.RegisterSingle<ICommandBus, CommandBus>();
     container.RegisterSingle<IEventBus, EventBus>();
     container.RegisterSingle<IBusLifetime, BusLifetime>();
 }
Exemplo n.º 8
0
        public static void RegisterSingleInterfacesAndType <T>(this Container container, IEnumerable <Type> types)
        {
            var ifaceType = typeof(T);

            foreach (var s in types)
            {
                container.RegisterSingle(s, s);
                foreach (var i in s.GetInterfaces().Where(x => Predicate(x, ifaceType)))
                {
                    container.RegisterSingle(i, () => container.GetInstance(s));
                }
            }
        }
Exemplo n.º 9
0
        public static void RegisterImplementations()
        {
            var container = new Container();

            container.RegisterSingle<IDbContextFactory, DbContextFactory>();
            container.RegisterSingle<ICacheStorage<string>, LocalCacheStorage>();
            container.RegisterSingle<ILogger, NLogLogger>();

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
        }
Exemplo n.º 10
0
        public void Register(Container container)
        {
            container.RegisterSingle<IUserStore<ApplicationUser, Guid>, ApplicationUserStore>();
            container.RegisterSingle<IIdentityMessageService, ApplicationIdentityMessageService>();
            container.RegisterSingle<ApplicationUserManager>();

            container.RegisterPerWebRequest<ApplicationSignInManager>();
            container.RegisterPerWebRequest<IUserContext, UserContext>();
            container.RegisterPerWebRequest<IContextService, ContextService>();

            container.RegisterMvcIntegratedFilterProvider();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
        private static void InitSiteContainer(Container container)
        {
            container.Register<Fx.Domain.Account.IService.IAccountService, Fx.Domain.Account.UserAccountService>();
            container.Register<Fx.Domain.FxSite.IService.IChannelService, Fx.Domain.FxSite.ChannelService>();
            container.Register<Fx.Domain.FxSite.IService.ISite, Fx.Domain.FxSite.SiteService>();

            container.Register<Fx.Domain.FxSite.IService.IGoods, Fx.Domain.FxSite.GoodsService>();
            container.Register<Fx.Domain.FxSite.IService.ICar, Fx.Domain.FxSite.CarService>();
            container.Register<Fx.Domain.FxSite.IService.IHouse, Fx.Domain.FxSite.HouseService>();

            //FxGoods
            container.Register<Fx.Domain.FxGoods.IService.ITransferGoods, Fx.Domain.FxGoods.FxTransferGoodService>();
            container.Register<Fx.Domain.FxGoods.IService.IBuyGoods, Fx.Domain.FxGoods.FxBuyGoodsService>();

            //FxCar
            container.Register<Fx.Domain.FxCar.IService.ITransferCar, Fx.Domain.FxCar.FxTransferCarService>();
            container.Register<Fx.Domain.FxCar.IService.IBuyCar, Fx.Domain.FxCar.FxBuyCarService>();

            //FxHouse
            container.Register<Fx.Domain.FxHouse.IService.ITransferHouse, Fx.Domain.FxHouse.FxTransferHouseService>();
            container.Register<Fx.Domain.FxHouse.IService.IBuyHouse, Fx.Domain.FxHouse.FxBuyHouseService>();

            //�������
            container.RegisterSingle<Fx.Infrastructure.Caching.ICacheManager, Fx.Infrastructure.Caching.CacheManager>();
        }
Exemplo n.º 12
0
        private static void InitializeContainer(Container container)
        {
            container.RegisterPerWebRequest<IDataContext, DataContext>();

            container.RegisterPerWebRequest<IUsersRepository, UsersRepository>();
            container.RegisterPerWebRequest<IRolesRepository, RolesRepository>();

            container.RegisterSingle<IConstantsProvider, DevConstantProvider>();

            container.RegisterPerWebRequest<IAuthenticationService, AuthenticationService>();
            container.RegisterPerWebRequest<IUsersService, UsersService>();
            container.RegisterPerWebRequest<IRolesService, RolesService>();
            container.RegisterSingle<IHashService, HashService>();

            container.RegisterPerWebRequest<ICurrentUserProxy, CurrentUserProxy>();
        }
        /// <summary>
        /// Discovers any Func dependencies of the specified type and attempts to register them.
        /// </summary>
        /// <param name="concreteType">Concrete type for which the dependencies should be discovered
        /// and registered</param>
        /// <param name="container">SimpleInjector container in which the dependencies should be registered.</param>
        /// <param name="options">Options to apply to the discovery and registration process.</param>
        public void RegisterDependencies(Type concreteType, Container container, IAutoRegistrationOptions options)
        {
            foreach (var ctor in concreteType.GetConstructors().Where((x) => x.IsPublic))
            {
                foreach (var param in ctor.GetParameters().Where((x) => x.ParameterType.Name.StartsWith("Func`")))
                {
                    var funcParamType = param.ParameterType;
                    var genericArgType = funcParamType.GenericTypeArguments.FirstOrDefault();

                    if (genericArgType != null 
                     && genericArgType.IsInterface 
                     && options.AutoRegistrationEnabledProvider.IsAutoRegistrationEnabled(genericArgType))
                    {
                        //Since Funcs<> do not retain any state and the wrapped Func<> accounts for the
                        //lifestyle of the object, it can always be made singleton, while the wrapped
                        //type may be transient.
                        container.RegisterSingle(funcParamType, () =>
                        {
                            //Create a Func<> with the container in context to create an instance of the type
                            var method = typeof(ContextualFuncCreationHelper).GetMethod("GetFunc").MakeGenericMethod(genericArgType);
                            var funcInstance = new ContextualFuncCreationHelper(container);

                            return Delegate.CreateDelegate(funcParamType, funcInstance, method);
                        });
                    }
                }
            }
        }
Exemplo n.º 14
0
        public static Container RegisterTypes()
        {
            Container container = new Container();

            #region Queue IoC

            container.RegisterSingle<IPublisher>(new Publisher(container));

            container.RegisterSingle(new MessageEmitter(container));

            container.RegisterSingle(new RabbitMQIntegrationModule(container));

            #endregion

            container.Verify();
            return container;
        }
        private static void InitJobContainer(Container container)
        {
            container.RegisterSingle<FxTask.AppSettings>();
            container.RegisterSingle<FxTask.Filter>();

            //FxTaskFxCar
            container.Register<Fx.Domain.FxCar.IService.ICarBuyJob, Fx.Domain.FxCar.CarBuyJobService>();
            container.Register<Fx.Domain.FxCar.IService.ICarTransferJob, Fx.Domain.FxCar.CarTransferJobService>();


            //FxTaskFxGoods
            container.Register<Fx.Domain.FxGoods.IService.IGoodsBuyJob, Fx.Domain.FxGoods.GoodsBuyJobService>();
            container.Register<Fx.Domain.FxGoods.IService.IGoodsTransferJob, Fx.Domain.FxGoods.GoodsTransferJobService>();

            //FxTaskFxHouse
            container.Register<Fx.Domain.FxHouse.IService.IHouseBuyJob, Fx.Domain.FxHouse.HouseBuyJobService>();
            container.Register<Fx.Domain.FxHouse.IService.IHouseTransferJob, Fx.Domain.FxHouse.HouseTransferJobService>();
        }
Exemplo n.º 16
0
 public void Execute_InvokesQueryHandler_UsingContainerForResolution()
 {
     var container = new Container();
     container.RegisterSingle<IProcessQueries, QueryProcessor>();
     container.RegisterManyForOpenGeneric(typeof(IHandleQuery<,>), Assembly.GetExecutingAssembly());
     container.Verify();
     var queries = container.GetInstance<IProcessQueries>();
     var result = queries.Execute(new FakeQueryWithoutValidator());
     result.ShouldEqual("faked");
 }
Exemplo n.º 17
0
        public void Register(Container container)
        {
            container.RegisterSingle(() =>
            {
                LicenseUtils.RegisterLicense("2283-e1JlZjoyMjgzLE5hbWU6TWVkWENoYW5nZSxUeXBlOkluZGllLEhhc2g6TU" +
                "FyaTVzNGdQcEdlc0pqd1ZIUXVlL0lacDBZcCt3TkFLY0UyMTlJblBuMzRLNWFRb" +
                "HBYN204aGkrQXlRYzUvZnNVUlZzWXd4NjR0OFlXZEpjNUNYRTdnMjBLR0ZjQmhG" +
                "dTFNMHZVazJqcHdQb1RrbStDaHNPRm11Qm50TnZzOTkwcHAzRkxtTC9idThMekN" +
                "lTVRndFBORzBuREZ0WGJUdzdRMi80K09lQ2tZPSxFeHBpcnk6MjAxNi0wMi0xOX" +
                "0=");

                var rabbitMqHost = ConfigurationManager.AppSettings["RabbitMQHost"];
                if (string.IsNullOrEmpty(rabbitMqHost)) throw new Exception("You must provide a 'RabbitMQHost' app setting.");
                return new RabbitMqServer(rabbitMqHost);
            });
            container.RegisterSingle<ICommandBus, CommandBus>();
            container.RegisterSingle<IEventBus, EventBus>();
            container.RegisterSingle<IBusLifetime, BusLifetime>();
        }
        private static void InitCacheContainer(Container container)
        {
            //�������
            container.RegisterSingle<Fx.Infrastructure.Caching.ICacheManager, Fx.Infrastructure.Caching.CacheManager>();
            container.RegisterSingle<FxCacheService.FxGoods.GoodsCache>();
            container.RegisterSingle<FxCacheService.FxHouse.HouseCache>();
            container.RegisterSingle<FxCacheService.FxCar.CarCache>();
            container.RegisterSingle<FxCacheService.FxSite.SiteCache>();
            //�����ѯ����  Ϊʲô��ʹ�ýӿ�ע�᣿ISiteSearch<CarBuyInfo> ���ֶ���һ���� ���ڻ���
            container.Register<Fx.Domain.FxCar.Search.CarBuySearchService>();
            container.Register<Fx.Domain.FxCar.Search.CarTransferSearchService>();
            container.Register<Fx.Domain.FxGoods.Search.GoodsBuySearchService>();
            container.Register<Fx.Domain.FxGoods.Search.GoodsTransferSearchService>();
            container.Register<Fx.Domain.FxHouse.Search.HouseBuySearchService>();
            container.Register<Fx.Domain.FxHouse.Search.HouseTransferSearchService>();

            container.Register<Fx.Domain.FxCar.IService.IGlobalCacheCar, Fx.Domain.FxCar.GlobalCacheCar>();
            container.Register<Fx.Domain.FxGoods.IService.IGlobalCacheGoods, Fx.Domain.FxGoods.GlobalCacheGoods>();
            container.Register<Fx.Domain.FxHouse.IService.IGolbalCacheHouse, Fx.Domain.FxHouse.GlobalHouseCache>();
        }
 private static void InitializeContainer(Container container)
 {
     container.RegisterPerWebRequest<IDbConnection>(CreateConnection);
     container.RegisterSingle<Logger>();
     container.Register<IDbCommand>(() => new SqlCommand(string.Empty,container.GetInstance<IDbConnection>() as SqlConnection));
     container.RegisterPerWebRequest<IContactRepository, ContactRepository>();
     //container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(Contact).Assembly);
     container.RegisterPerWebRequest<ICommandHandler<CreateContactCommand>, CreateContactHandler>();
     container.RegisterDecorator(typeof (ICommandHandler<>), typeof (CommandAuditingHandler<>));
     container.Register<UnitOfWork>();
 }
Exemplo n.º 20
0
 public void ValidateQuery_InvokesValidator_UsingContainerForResolution()
 {
     var container = new Container();
     container.RegisterSingle<IProcessValidation, ValidationProcessor>();
     container.RegisterManyForOpenGeneric(typeof(IValidator<>), Assembly.GetExecutingAssembly());
     container.Verify();
     var validation = container.GetInstance<IProcessValidation>();
     var result = validation.Validate(new FakeQueryWithValidator { InputValue = null });
     result.IsValid.ShouldBeFalse();
     result.Errors.Count.ShouldEqual(1);
 }
 private static void InitCacheContainer(Container container)
 {
     //缓存服务
     container.RegisterSingle<Fx.Infrastructure.Caching.ICacheManager, Fx.Infrastructure.Caching.CacheManager>();
     container.RegisterSingle<FxCacheService.FxGoods.GoodsCache>();
     container.RegisterSingle<FxCacheService.FxHouse.HouseCache>();
     container.RegisterSingle<FxCacheService.FxCar.CarCache>();
     container.RegisterSingle<FxCacheService.FxSite.SiteCache>();
     //缓存查询服务  为什么不使用接口注册?ISiteSearch<CarBuyInfo> 保持对外一致性 用于缓存
     container.Register<Fx.Domain.FxCar.Search.CarBuySearchService>();
     container.Register<Fx.Domain.FxCar.Search.CarTransferSearchService>();
     container.Register<Fx.Domain.FxGoods.Search.GoodsBuySearchService>();
     container.Register<Fx.Domain.FxGoods.Search.GoodsTransferSearchService>();
     container.Register<Fx.Domain.FxHouse.Search.HouseBuySearchService>();
     container.Register<Fx.Domain.FxHouse.Search.HouseTransferSearchService>();
     //领域层提供给缓存服务层专门拉取数据的接口
     container.Register<Fx.Domain.FxCar.IService.IGlobalCacheCar,Fx.Domain.FxCar.GlobalCacheCar>();
     container.Register<Fx.Domain.FxGoods.IService.IGlobalCacheGoods, Fx.Domain.FxGoods.GlobalCacheGoods>();
     container.Register<Fx.Domain.FxHouse.IService.IGolbalCacheHouse, Fx.Domain.FxHouse.GlobalHouseCache>();
 }
Exemplo n.º 22
0
        private static void RegisterRavenDB(Container container)
        {
            var store = new DocumentStore { ConnectionStringName = "Server" };

            store.Initialize();

            container.RegisterSingle<IDocumentStore>(store);

            container.RegisterPerWebRequest<IAsyncDocumentSession>(() => store.OpenAsyncSession());

            container.RegisterPerWebRequest<IDocumentSession>(() => store.OpenSession());
        }
Exemplo n.º 23
0
        public static void Configure(Container _)
        {
            IBoardLotConfig[] lotConfigs = new IBoardLotConfig[]
            {
                GetBoardLotConfig('A'),
                GetBoardLotConfig('B'),
                GetBoardLotConfig('C'),
                GetBoardLotConfig('D'),
                GetBoardLotConfig('E'),
                GetBoardLotConfig('F'),
                GetBoardLotConfig('G'),
                GetBoardLotConfig('H'),
                GetBoardLotConfig('I'),
                GetBoardLotConfig('J'),
                GetBoardLotConfig('K'),
                GetBoardLotConfig('L'),
                GetBoardLotConfig('M'),
                GetBoardLotConfig('N'),
                GetBoardLotConfig('O')
            };
            _.RegisterSingle<IBoardLotConfig[]>(lotConfigs);

            IFeesConfig feesConfig = Configurator.Configurator.Configure<FeesConfig>("sell"); // TODO: Contextual injection.
            _.RegisterSingle<IFeesConfig>(feesConfig);

            IMathConfig mathConfig = Configurator.Configurator.Configure<MathConfig>("math");
            _.RegisterSingle<IMathConfig>(mathConfig);

            _.RegisterSingle<IBoardLotCalculatorService, BoardLotCalculatorService>();
            _.RegisterSingle<IFeeCalculatorService, FeeCalculatorService>();
            _.RegisterSingle<IProfitLossCalculatorService, ProfitLossCalculatorService>();
        }
Exemplo n.º 24
0
        private static void InitializeContainer(Container container)
        {
            DocumentStore ds = new DocumentStore { ConnectionStringName = "RavenHQ" };
            var something = ds.Url;
            ds.Initialize();

            container.RegisterSingle<IDocumentStore>(ds);
            container.Register<IGenericRepository<Idea>, GenericRepository<Idea>>();
            container.Register<IIdeaService, IdeaService>();

            // For instance:
            // container.Register<IUserRepository, SqlUserRepository>();
        }
Exemplo n.º 25
0
        public void Execute_InvokesCommandHandler_UsingContainerForResolution()
        {
            var container = new Container();
            container.RegisterSingle<IProcessCommands, CommandProcessor>();
            container.RegisterManyForOpenGeneric(typeof(IHandleCommand<>), Assembly.GetExecutingAssembly());
            container.Verify();
            var commands = container.GetInstance<IProcessCommands>();
            var command = new FakeCommandWithoutValidator();

            commands.Execute(command);

            command.ReturnValue.ShouldEqual("faked");
        }
        private static void InitializeContainer(Container container)
        {
            // Please note that if you updated the SimpleInjector.MVC3 package from a previous version, this
            // SimpleInjectorInitializer class replaces the previous SimpleInjectorMVC3 class. You should
            // move the registrations from the old SimpleInjectorMVC3.InitializeContainer to this method,
            // and remove the SimpleInjectorMVC3 and SimpleInjectorMVC3Extensions class from the App_Start
            // folder.
            container.RegisterSingle<Fx.Infrastructure.Caching.ICacheManager, Fx.Infrastructure.Caching.CacheManager>();
            container.RegisterSingle<FxTask.AppSettings>();
            container.RegisterSingle<FxTask.Filter>();

            //FxTaskFxCar
            container.Register<Fx.Domain.FxCar.IService.ICarBuyJob, Fx.Domain.FxCar.CarBuyJobService>();
            container.Register<Fx.Domain.FxCar.IService.ICarTransferJob, Fx.Domain.FxCar.CarTransferJobService>();

            //FxTaskFxGoods
            container.Register<Fx.Domain.FxGoods.IService.IGoodsBuyJob, Fx.Domain.FxGoods.GoodsBuyJobService>();
            container.Register<Fx.Domain.FxGoods.IService.IGoodsTransferJob, Fx.Domain.FxGoods.GoodsTransferJobService>();

            //FxTaskFxHouse
            container.Register<Fx.Domain.FxHouse.IService.IHouseBuyJob, Fx.Domain.FxHouse.HouseBuyJobService>();
            container.Register<Fx.Domain.FxHouse.IService.IHouseTransferJob, Fx.Domain.FxHouse.HouseTransferJobService>();
        }
Exemplo n.º 27
0
        private static Container Bootstrap()
        {
            var container = new Container();

            // register database types
            container.Register<IDatabaseInitializer<UCosmicContext>, BrownfieldInitializer>();
            container.Register<ISeedData, BrownfieldSeeder>();
            container.Register<UCosmicContext>();
            container.Register<IWrapDataConcerns, DataConcernsWrapper>();
            container.RegisterInitializer<UCosmicContext>(container.InjectProperties);

            // register browsers
            container.RegisterSingle(() => new ChromeDriver(GetChromeDriverDirectory()));
            container.RegisterSingle(() => new InternetExplorerDriver());
            container.RegisterSingle(() => new FirefoxDriver());
            var browsers = AllBrowsers(container);
            container.RegisterAll(browsers);

            // register other stuff
            container.Register<IManageConfigurations, DotNetConfigurationManager>();

            container.Verify();
            return container;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SimpleInjectorContainerProvider" /> class.
        /// </summary>
        public SimpleInjectorContainerProvider()
        {
            container = new SimpleInjector.Container();

            container.Register <HttpContextBase>(() => new HttpContextWrapper(HttpContext.Current));

            var controllerFactory = new DefaultControllerFactory();

            container.RegisterSingle <IControllerFactory>(controllerFactory);
            container.RegisterSingle <IControllerActivator>(new SimpleInjectorControllerActivator(container));
            container.RegisterSingle <IActionInvoker>(new ControllerActionInvoker());
            container.RegisterSingle <ITempDataProvider>(new SessionStateTempDataProvider());
            container.RegisterSingle <RouteCollection>(RouteTable.Routes);
            container.RegisterSingle <IAsyncActionInvoker>(new AsyncControllerActionInvoker());
            container.RegisterSingle <IViewPageActivator>(new SimpleInjectorViewPageActivator(container));
            container.RegisterSingle <ModelMetadataProvider>(System.Web.Mvc.ModelMetadataProviders.Current);
        }
Exemplo n.º 29
0
        public override IServiceProvider Bootstrap() {
            var container = new Container();
            container.Options.AllowOverridingRegistrations = true;
            container.Options.PropertySelectionBehavior = new InjectAttributePropertySelectionBehavior();

            container.RegisterPackage<Bootstrapper>();

            if (Settings.Current.EnableRedis)
                container.RegisterSingle<IQueue<EventMigrationBatch>>(() => new RedisQueue<EventMigrationBatch>(container.GetInstance<ConnectionMultiplexer>(), retries: 5, workItemTimeout: TimeSpan.FromHours(2)));
            else
                container.RegisterSingle<IQueue<EventMigrationBatch>>(() => new InMemoryQueue<EventMigrationBatch>(retries: 5, workItemTimeout: TimeSpan.FromHours(2)));

            Assembly insulationAssembly = null;
            try {
                insulationAssembly = Assembly.Load("Exceptionless.Insulation");
            } catch (Exception ex) {
                Log.Error().Message("Unable to load the insulation asssembly.").Exception(ex).Write();
            }

            if (insulationAssembly != null)
                container.RegisterPackages(new[] { insulationAssembly });

            return container;
        }
        public static void Bootstrap(Container container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            container.RegisterSingle<IValidator>(new DataAnnotationsValidator(container));

            container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), Assembly.GetExecutingAssembly());
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AuthorizationCommandHandlerDecorator<>));

            container.RegisterManyForOpenGeneric(typeof(IQueryHandler<,>), Assembly.GetExecutingAssembly());
            container.RegisterDecorator(typeof(IQueryHandler<,>), typeof(AuthorizationQueryHandlerDecorator<,>));
        }
Exemplo n.º 31
0
 protected void Application_Start()
 {
     //new simpleinjector container
     Container container = new Container();
     //register objects
     CloudStorageAccount account = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
     container.Register(() => account);
     container.Register<IImageBlobRepository, ImageBlobRepository>();
     container.RegisterSingle(LogManager.GetLogger("NLogger"));
     container.Verify();
     DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
        /// <summary>
        /// Discovers any Lazy dependencies of the specified type and attempts to register them.
        /// </summary>
        /// <param name="concreteType">Concrete type for which the dependencies should be discovered
        /// and registered</param>
        /// <param name="container">SimpleInjector container in which the dependencies should be registered.</param>
        /// <param name="options">Options to apply to the discovery and registration process.</param>
        public void RegisterDependencies(Type concreteType, Container container, IAutoRegistrationOptions options)
        {
            foreach (var ctor in concreteType.GetConstructors().Where((x) => x.IsPublic))
            {
                foreach (var param in ctor.GetParameters().Where((x) => x.ParameterType.Name.StartsWith("Lazy`")))
                {
                    var funcParamType = param.ParameterType;
                    var genericArgType = funcParamType.GenericTypeArguments.FirstOrDefault();

                    if (genericArgType != null 
                     && genericArgType.IsInterface 
                     && options.AutoRegistrationEnabledProvider.IsAutoRegistrationEnabled(genericArgType))
                    {
                        Lifestyle lifestyle = options.LifestyleResolver.GetLifestyle(genericArgType);

                        if (lifestyle == null)
                        {
                            throw new Exception(string.Format("Lifestyle not defined for wrapped type of Lazy<{0}>", genericArgType.Name));
                        }

                        Func<object> creationDelegate = () =>
                        {
                            //First create a Func<> with the container in context to create an instance of the type
                            var method = typeof(ContextualFuncCreationHelper).GetMethod("GetFunc").MakeGenericMethod(genericArgType);
                            var funcType = typeof(Func<>).MakeGenericType(genericArgType);
                            var funcInstance = new ContextualFuncCreationHelper(container);
                            
                            var dgt = Delegate.CreateDelegate(funcType, funcInstance, method);

                            //Create lazy with the Func delegate as a parameter
                            return Activator.CreateInstance(funcParamType, dgt);
                        };

                        //Since the Lazy<> acts as a singleton and retains state, we need to determine if the Lazy<>
                        //should be transient or singleton
                        if (lifestyle == Lifestyle.Singleton)
                        {
                            container.RegisterSingle(funcParamType, creationDelegate);
                        }
                        else
                        {
                            container.Register(funcParamType, creationDelegate);
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
        public static void RegisterMvcIntegratedFilterProvider(this Container container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            RequiresFilterProviderNotRegistered(container);

            var singletonFilterProvider = new SimpleInjectorFilterAttributeFilterProvider(container);

            container.RegisterSingle <IFilterProvider>(singletonFilterProvider);

            var providers = FilterProviders.Providers.OfType <FilterAttributeFilterProvider>().ToList();

            providers.ForEach(provider => FilterProviders.Providers.Remove(provider));

            FilterProviders.Providers.Add(singletonFilterProvider);
        }
Exemplo n.º 34
0
        /// <summary>
        /// Register an instance with the container.
        /// </summary>
        /// <remarks>
        /// <para>
        /// Instance registration is much like registering a type with <see cref="LifetimeType.Singleton" />,
        /// except that instead of the container creating the instance the first time it is requested, the
        /// instance is already created outside the container and that instance is added to the container.
        /// </para>
        /// </remarks>
        /// <param name="serviceType"><see cref="System.Type" /> of the service that will be requested.</param>
        /// <param name="instance">The instance.</param>
        /// <returns>The <see cref="IContainerProvider" /> object that this method was called on.</returns>
        public override IContainerProvider RegisterInstance(Type serviceType, object instance)
        {
            container.RegisterSingle(serviceType, instance);

            return(this);
        }