protected override void ConfigureContainer()
        {
            // Register global settings
            var globalSettings = new GlobalSettings
            {
                DefaultGamesSettingsFolder     = $@"{Directory.GetCurrentDirectory()}\GameSettings\",
                DefaultInstallFolderConfigFile = $@"{Directory.GetCurrentDirectory()}\DefaultInstallFolders.json",
                CustomInstallFolderConfigFile  = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\VGIS\CustomInstallFolders.json",
                CustomGamesSettingsFolder      = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\VGIS\GameSettings\"
            };

            Container.RegisterInstance(globalSettings, new ContainerControlledLifetimeManager());

            var crowdsourcingSettings = new ApiEndpointSettings
            {
                EndpointUrl = "https://vgisapi.nicolas-constant.com"
            };

            Container.RegisterInstance(crowdsourcingSettings, new ContainerControlledLifetimeManager());

            // Register repositories
            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(x => x.Name.EndsWith("Repository")),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled);

            // Register services
            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(x => x.Name.EndsWith("Service")),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled);

            // Register all other types
            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            base.ConfigureContainer();
        }
Exemple #2
0
        public void RegistersAllTypesWithHelperMethods()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(AllClasses.FromLoadedAssemblies(),
                                    WithMappings.FromAllInterfaces,
                                    WithName.TypeName,
                                    WithLifetime.ContainerControlled, overwriteExistingMappings: true);

            var registrations = container.Registrations.Where(r => r.MappedToType == typeof(MockLogger)).ToArray();

            Assert.AreEqual(1, registrations.Length);

            var mappingRegistration = registrations.Single(r => r.RegisteredType == typeof(ILogger));

            Assert.AreSame(typeof(ILogger), mappingRegistration.RegisteredType);
            Assert.AreSame(typeof(MockLogger), mappingRegistration.MappedToType);
            Assert.AreEqual("MockLogger", mappingRegistration.Name);
            Assert.IsInstanceOfType(mappingRegistration.LifetimeManager, typeof(ContainerControlledLifetimeManager));
        }
Exemple #3
0
        static void RegistrationByConventionWithInterception()
        {
            using (var container = new UnityContainer())
            {
                container.AddNewExtension <Interception>();
                container.RegisterTypes(
                    AllClasses.FromLoadedAssemblies().Where(t => t.Namespace == "OtherUnitySamples"),
                    WithMappings.FromMatchingInterface,
                    getInjectionMembers: t => new InjectionMember[] { new Interceptor <VirtualMethodInterceptor>(), new InterceptionBehavior <LoggingInterceptionBehavior>() });


                container.RegisterType <TenantStore>(new InjectionConstructor("Adatum"));
                container.RegisterType <SurveyStore>(new InjectionConstructor("Adatum"));

                var tenantStore = container.Resolve <ITenantStore>();
                tenantStore.Save();
                var surveyStore = container.Resolve <ISurveyStore>();
                surveyStore.Save();
            }
        }
Exemple #4
0
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterTypes
            (
                types: AllClasses.FromLoadedAssemblies().Where(x => x.Namespace.Contains(DefaultNameSpacePreffix)),
                getFromTypes: WithMappings.FromMatchingInterface,
                getName: WithName.Default,
                getLifetimeManager: WithLifetime.Custom <TransientLifetimeManager>,
                getInjectionMembers: null,
                overwriteExistingMappings: true
            );

            var connectionString = WebConfigurationManager.ConnectionStrings["SampleDB"].ToString();

            container.RegisterType <IDatabaseConnectionFactory, DatabaseConnectionFactory>
            (
                new TransientLifetimeManager(),
                new InjectionConstructor(connectionString)
            );
        }
        private Type GetValidatorType(Type type)
        {
            if (type == null)
            {
                return(null);
            }

            var abstractValidatorType = typeof(AbstractValidator <>);
            var validatorForType      = abstractValidatorType.MakeGenericType(type);

            var types = AllClasses.FromLoadedAssemblies().
                        Where(t => validatorForType.IsAssignableFrom(t)).ToList();

            if (types.Any())
            {
                return(types.FirstOrDefault());
            }

            return(null);
        }
Exemple #6
0
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // Register All Types by Convention by default
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Transient);

            // Overwrite All Types marked as Singleton
            //container.RegisterTypes(
            //    AllClasses.FromLoadedAssemblies()
            //        .Where(t => t.GetCustomAttributes(typeof(SingletonAttribute), true).Any()),
            //    WithMappings.FromMatchingInterface,
            //    WithName.Default,
            //    WithLifetime.ContainerControlled,
            //    null,
            //    true); // Overwrite existing mappings without throwing

            // container.RegisterType<IIdentity>(new InjectionFactory(_ => HttpContext.Current.User.Identity));
        }
Exemple #7
0
        static void RegistrationByConventionGenerics()
        {
            using (var container = new UnityContainer())
            {
                container.RegisterTypes(
                    // Registers open generics
                    AllClasses.FromLoadedAssemblies(),
                    WithMappings.FromMatchingInterface,
                    WithName.Default);

                // Add a registration of a closed generic
                container.RegisterType <ICustomerStore <TableStorage>, CustomerStore <TableStorage> >();
                DisplayRegistrations(container);

                // Uses the registration of the open generic type
                var blobCustomerStore = container.Resolve <ICustomerStore <BlobStorage> >();

                // Uses the registration of the closed generic type
                var tableCustomerStore = container.Resolve <ICustomerStore <TableStorage> >();
            }
        }
        private static void DesignTimeConfiguration(IUnityContainer container)
        {
            // register services
            container
            .RegisterType <IDependencyResolver, UnityHierarchicalDependencyResolver>(new ContainerControlledLifetimeManager())
            .RegisterType <IDarkSkyClient, ConfiguredDarkSkyClient>(new ContainerControlledLifetimeManager())
            .RegisterType <ILocationService, OfflineLocationService>(new HierarchicalLifetimeManager())
            .RegisterType <IForecastService, DarkSkyForecastService>(new HierarchicalLifetimeManager())
            .RegisterType <IDomainModelMapper, DomainModelMapper>(new ContainerControlledLifetimeManager())
            .RegisterType <ILanguageService, LanguageService>(new ContainerControlledLifetimeManager())
            .RegisterType <CancellationTokenSource>(
                new HierarchicalLifetimeManager(),
                new InjectionFactory(c => CancellationTokenSource.CreateLinkedTokenSource(ApplicationContext.MainCancellationTokenSource.Token)));

            // register all viewmodels as hierarchical
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(p => p.IsSubclassOf(typeof(ViewModelBase))),
                WithMappings.None,
                WithName.Default,
                WithLifetime.Hierarchical);
        }
Exemple #9
0
        public void ConfigureIoC()
        {
            _container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled);

            FluentNHibernateSQLiteCSharp.IOC.Bootstrapper.ConfigureIoC(_container);

            //_container.RegisterType<IDonatorsViewer, DonatorsViewer>();
            //_container.RegisterType<IDonatorService, DonatorService>();
            //_container.RegisterType<ISearchFilter<Donator>, SearchFilter<Donator>>();
            //_container.RegisterType<IQueryHelper<Donator>, QueryHelper<Donator>>();


            //_container.RegisterType<ITransactionsViewer, TransactionsViewer>();
            //_container.RegisterType<ITransactionService, TransactionService>();
            //_container.RegisterType<ISearchFilter<Transaction>, SearchFilter<Transaction>>();
            //_container.RegisterType<IQueryHelper<Transaction>, QueryHelper<Transaction>>();
        }
Exemple #10
0
        public static IUnityContainer RegisterServices(this IUnityContainer container)
        {
            //Register all services based on IService except IPrincipalService
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies()
                .Where(type => typeof(IService).IsAssignableFrom(type) &&
                       !typeof(IPrincipalService).IsAssignableFrom(type)),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve);

            //Register IPrincipalService
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies()
                .Where(type => typeof(IPrincipalService).IsAssignableFrom(type)),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Hierarchical);

            return(container);
        }
        static void AutoRegisterationDemo()
        {
            Console.WriteLine("\n<<< AutoRegisterDemo >>>");

            // 設定 Unity 容器:自動註冊型別
            var container = new UnityContainer();
            var classes   = from t in AllClasses.FromLoadedAssemblies()
                            where t.Name.IndexOf("Service") > 0
                            select t;

            container.RegisterTypes(
                classes,                        // 掃描目前已經載入此應用程式的全部組件。
                WithMappings.FromAllInterfaces, // 尋找所有介面。
                getName: WithName.TypeName,
                overwriteExistingMappings: false);

            // 解析物件
            var msgService = container.Resolve <IMessageService>("EmailService");

            msgService.SendMessage("Michael", "Hello!");
        }
        public static void RegisterTypesWithConvention(IUnityContainer container)
        {
            ConsoleHelper.WriteGreenLine("Register types with convention...");
            //using Unity.RegistrationByConvention
            //默认注册,无命名
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(t => t.Namespace.StartsWith("Practice.Unity.Calculator")),
                WithMappings.FromAllInterfaces,
                WithName.Default,
                WithLifetime.ContainerControlled,
                overwriteExistingMappings: true
                );
            //默认注册,以类型名称命名
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(t => t.Namespace.StartsWith("Practice.Unity.Calculator")),
                WithMappings.FromAllInterfaces,
                WithName.TypeName,
                WithLifetime.ContainerControlled,
                overwriteExistingMappings: false
                );
            foreach (var item in container.Registrations)
            {
                var name = string.IsNullOrWhiteSpace(item.Name) ? "null" : item.Name;
                Console.WriteLine(string.Format("+ {0} : {1} -> {2}", name, item.RegisteredType, item.MappedToType));
            }
            var calculator = container.Resolve <ICalculator>();

            Console.WriteLine(string.Format("ICalculator instance #{0} is running...", calculator.GetHashCode()));
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    calculator.Calculate(string.Format("{0} {1} {2}", RandomHelper.NextInt(0, 10), "+-*/"[RandomHelper.NextInt(0, 4)], RandomHelper.NextInt(0, 10)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
Exemple #13
0
        public void WhenRegisteringFromLoadedTypesAndSkipUnityAssemblies_FindIInterceptor()
        {
            IUnityContainer container = new UnityContainer();

            Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\AssemblyWithUnityInterface.dll");
            container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromAllInterfaces, WithName.TypeName, null, null, true);
            bool isInterceptorFound = false;

            foreach (var registration in container.Registrations)
            {
                if (registration.Name == null)
                {
                    continue;
                }

                if (registration.Name.Contains("MyInterceptorClass"))
                {
                    isInterceptorFound = true;
                }
            }
            Assert.IsTrue(isInterceptorFound);
        }
        public static void InjectAll(IUnityContainer container)
        {
            RepositoriesRegistraton.Register(container);

            Services.Impl.Services.Register(container);

            container.RegisterType <IExportDataService, ExportDataServiceImpl>();



            container.RegisterType <IEmailService, EmailServiceImpl>();



            container.RegisterType <IPluginFactory, PluginFactoryImpl>();

            container.RegisterType <IEmailSendingService, EmailSendingServiceImpl>();

            //TODO Automatically load all assemblies that start with JoinRpg.Experimental.Plugin.*
            container.RegisterTypes(AllClasses.FromLoadedAssemblies().Where(type => typeof(IPlugin).IsAssignableFrom(type)),
                                    WithMappings.FromAllInterfaces, WithName.TypeName);
        }
Exemple #15
0
        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            //container.RegisterType<IProteinRepository, ProteinRepository>(new InjectionConstructor("test data source"));
            //container.RegisterInstance(typeof (IProteinRepository), new ProteinRepository("test data source 123"));

            container.RegisterType <IProteinRepository, ProteinRepository>("StandardRepository",
                                                                           new InjectionConstructor("test"));
            container.RegisterType <IProteinRepository, DebugProteinRepository>("DebugRepository");

            var repositoryType = WebConfigurationManager.AppSettings["RepositoryType"];

            container.RegisterType <IProteinTrackingService, ProteinTrackingService>(
                new InjectionConstructor(container.Resolve <IProteinRepository>(repositoryType)));

            //container.RegisterType<IProteinTrackingService, ProteinTrackingService>();
            //container.RegisterType<IProteinRepository, ProteinRepository>();
        }
Exemple #16
0
        static void Main(string[] args)
        {
            ILogger logger = LogManager.GetCurrentClassLogger();

            IUnityContainer unitycontainer = new UnityContainer();

            //unitycontainer.RegisterType<IClass, Class1>();      //注入
            unitycontainer.RegisterInstance <ILogger>(logger);//跟上面一樣用意
            IClass IClassToDo = unitycontainer.Resolve <Class1>();

            //IClass class1 = new Class1(logger) ; //同上

            unitycontainer.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Hierarchical);
            //自動注入

            IClassToDo.Log();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <BModelProfile>();
            });

            var mapper = config.CreateMapper();
            var amodel = new AModel
            {
                Name = "Jeff",
                No   = 123
            };
            BModel bmodel = mapper.Map <BModel>(amodel);

            //Interface裡面宣告AA函式
            //Class1去接IClass
            //在program裡面呼叫Interface實作
        }
Exemple #17
0
        static void Main(string[] args)
        {
            // 自動掃描所指定的組件內容,根據不同引數設定,自動掃描組件內的所有型別,
            // 進而判斷與加入抽象介面型別與具體實作類別的對應關係,並且使用預設的注入物件生命週期
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(x => x.Namespace.Contains("UnityAutoRegistration")),
                WithMappings.FromAllInterfaces,
                WithName.Default,
                WithLifetime.ContainerControlled);

            // 進行抽象型別的具體實作物件的解析
            IMyMessage message = container.Resolve <IMyMessage>();

            // 執行取得物件的方法
            message.Write("Vulcan");

            Console.WriteLine();
            Console.WriteLine("顯示 IoC 容器中的所有型別對應");
            // 使用 IUnityContainer.Registrations 屬性值,
            // 來查看究竟有那些抽象型別與具體實作類別對應關係,加入到 DI Container 內呢?
            foreach (var item in container.Registrations)
            {
                if (item.MappedToType.Name == item.RegisteredType.Name)
                {
                    continue;
                }
                Console.WriteLine($"Name : {item.Name}");
                Console.WriteLine($"RegisteredType : {item.RegisteredType.Name}");
                Console.WriteLine($"MappedToType : {item.MappedToType.Name}");
                Console.WriteLine($"LifetimeManager : {item.LifetimeManager.LifetimeType.Name}");
                Console.WriteLine();
            }

            Console.WriteLine("Press any key for continuing...");
            Console.ReadKey();
        }
Exemple #18
0
        /// <summary>
        ///     Builds the unity container optionally loading the configuration and with a callback for registering additional
        ///     items.
        /// </summary>
        /// <param name="loadConfiguration">Whether or not the configuration should be loaded.</param>
        /// <param name="registrationCallback">A callback for loading additional configuration</param>
        /// <returns>A configured unity container.</returns>
        public IUnityContainer BuildUnityContainer(bool loadConfiguration, Action <IUnityContainer> registrationCallback)
        {
            if (Container == null)
            {
                Container = new UnityContainer();

                if (loadConfiguration)
                {
                    try
                    {
                        Container.LoadConfiguration();
                    }
                    catch (ArgumentNullException ex)
                    {
                        // do nothing--this is thrown if no configuration file or section was found.
                        Log.Info(
                            "Attempted to load the configuration but either no configuration file was found or the configuration section was empty.",
                            ex);
                    }
                }

                Container.RegisterInstance(typeof(IUnityContainer), Container, new ContainerControlledLifetimeManager());

                if (registrationCallback != null)
                {
                    registrationCallback.Invoke(Container);
                }

                IList <Type> types = AllClasses.FromLoadedAssemblies().Where(t => t.Namespace != null && t.Namespace.StartsWith("DatabaseDeploy")).ToList();
                Container.RegisterTypes(types, WithMappings.FromMatchingInterface, WithName.Default);
            }

            //// Add any additional registrations here or in the configuration file.
            // this is a temporary registration that is overridden at a later point.
            // Container.RegisterType(typeof(IDatabaseService), typeof(SqlServerDatabaseService));
            Container.RegisterType(typeof(IConfigurationService), typeof(ConfigurationService), new ContainerControlledLifetimeManager());
            return(Container);
        }
        private static void AutoRegisterInterfaces(IUnityContainer container)
        {
            var allowedRootNamespaces = new[] { "PhanCongGiangDay", "Lib" };

            var interfacesWithOneImplementation = AllClasses.FromLoadedAssemblies()
                                                  .Where(TypeNamespacesStartWith(allowedRootNamespaces))
                                                  .SelectMany(t =>
                                                              t.GetInterfaces()
                                                              .Select(i => new
            {
                ClassType = t,
                Interface = i
            }))
                                                  .Where(x => !container.IsRegistered(x.Interface))
                                                  .GroupBy(x => x.Interface)
                                                  .Where(x => x.Count() == 1)
                                                  .SelectMany(x => x);

            foreach (var registerTypePair in interfacesWithOneImplementation)
            {
                container.RegisterType(registerTypePair.Interface, registerTypePair.ClassType);
            }
        }
Exemple #20
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterTypes
            (
                types: AllClasses.FromLoadedAssemblies().Where(x => x.Namespace.Contains("YCRCPracticeWebApp")),
                getFromTypes: WithMappings.FromMatchingInterface,
                getName: WithName.Default,
                getLifetimeManager: WithLifetime.Custom <TransientLifetimeManager>,
                getInjectionMembers: null,
                overwriteExistingMappings: true
            );


            container.RegisterType <DbContext, NorthwindEntities>
            (
                new PerRequestLifetimeManager()
            );

            container.RegisterType <ICacheProvider, MemoryCacheProvider>
            (
                new PerRequestLifetimeManager()
            );
        }
Exemple #21
0
        //************************************************************************
        /// <summary>
        /// Unityコンテナを設定する。
        /// </summary>
        //************************************************************************
        protected override void ConfigureContainer(IUnityContainer container)
        {
            // Interceptionを拡張
            container.AddNewExtension <Interception>();

            // Interceptionの設定
            container.Configure <Interception>().AddPolicy("Server")
            .AddMatchingRule(new CustomAttributeMatchingRule(typeof(UseTransactionAttribute), true));

            // Injectionの設定
            // IBaseServiceを継承するインターフェースを登録
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(t => t.GetInterfaces().Contains(typeof(IBaseService))),
                WithMappings.FromMatchingInterface,
                getInjectionMembers: t => new InjectionMember[]
            {
                new Interceptor <InterfaceInterceptor>(),
                new InterceptionBehavior <PolicyInjectionBehavior>()
            });

            // DbContextを登録
            container.RegisterType <BaseDbContext>(new HierarchicalLifetimeManager());
        }
Exemple #22
0
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.AddNewExtension <Interception>();

            //Hack here: Added custom extension method to solve circular dependency issue for injection members. This matching interface checks for name of class that matches the interface name.
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().WithMatchingInterface(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve, getInjectionMembers: c => new InjectionMember[]
            {
                new Interceptor <InterfaceInterceptor>(),
                new InterceptionBehavior <LoggingInterceptor>()
            });

            container = RegisterContainer(container);

            //container.AddNewExtension<LazyExtension>();

            return(container);
        }
Exemple #23
0
        public static void Register(HttpConfiguration config)
        {
            var container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve);

            config.DependencyResolver = new UnityResolver(container);

            // Конфигурация и службы веб-API

            // Маршруты веб-API
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "PhonebookApp/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();


            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);
            // container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
            container.RegisterType(
                typeof(IRepository <>),
                typeof(Repository <>),
                new InjectionConstructor());
            container.RegisterInstance <IHttpControllerActivator>(new UnityHttpControllerActivator(container));

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
Exemple #25
0
        public static IUnityContainer BuildUnityContainer(IUnityContainer container)
        {
            // special case for factory method
            container.RegisterType <IDbContextFactory, DefaultDbContextFactory>(new PerResolveLifetimeManager());

            // register all your components with the container
            // it is NOT necessary to register controllers here
            // prefer using conventions as much as possible
            var types = AllClasses
                        .FromLoadedAssemblies()
                        .Where(predicate => predicate.Namespace != null &&
                               predicate.Namespace.StartsWith("DaiPhatDat") &&
                               !string.IsNullOrEmpty(predicate.AssemblyQualifiedName) &&
                               !typeof(Controller).IsAssignableFrom(predicate) &&
                               !predicate.IsAbstract &&
                               !predicate.IsInterface)
                        .ToList();


            #region HEADER INTERFACES AND CONCRETES IMPLEMENT

            container.RegisterTypes(types,
                                    WithMappings.FromMatchingInterface,
                                    WithName.Default,
                                    WithLifetime.PerResolve);

            #endregion HEADER INTERFACES AND CONCRETES IMPLEMENT

            #region AUTOMAPPER

            MappingRegistration(container, types);

            #endregion AUTOMAPPER

            return(container);
        }
Exemple #26
0
        public static void Register(HttpConfiguration config)
        {
            var container = new UnityContainer();

            var applicationDbContext = new ApplicationDatabaseContext();
            var userStore            = new UserStore <Person>(applicationDbContext);

            container.RegisterInstance(
                typeof(ApplicationDatabaseContext), applicationDbContext);

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies()
                .Where(
                    type =>
                    (typeof(IManager).IsAssignableFrom(type) || typeof(IStore).IsAssignableFrom(type)) &&
                    !type.IsAbstract && !type.IsInterface),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve);
            container.RegisterType <IEmailManager, EmailManager>();
            var userManager = AuthConfig.ConfigureUserManager(userStore, null);

            container.RegisterInstance(typeof(UserManager <Person>), userManager);
            container.RegisterInstance(typeof(IUserStore <Person>), userStore);
            // Web API configuration and services
            config.DependencyResolver = new UnityDependencyResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
        public static void RegisterWebApiComponents()
        {
            Container  = new UnityContainer();
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile("log-{Date}.txt")
                         .CreateLogger();



            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(x => x.GetInterfaces().Contains(typeof(ISingletonDependency))),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled
                );

            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(x => x.GetInterfaces().Contains(typeof(ITransientDependency))),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Transient
                );
        }
Exemple #28
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();
            container.RegisterType <HttpContextBase>(new PerRequestLifetimeManager(), new InjectionFactory(_ => new HttpContextWrapper(HttpContext.Current)));
            container.RegisterType <HttpRequestBase>(new PerRequestLifetimeManager(), new InjectionFactory(_ => new HttpRequestWrapper(HttpContext.Current.Request)));
            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();
            container.RegisterType <IDatabaseFactory <PayrollBureauDatabase>, PayrollBureauDatabaseFactory>(new InjectionConstructor(
                                                                                                                new InjectionParameter <string>(ConfigHelper.DefaultConnection)
                                                                                                                ));

            // Register everything in these namespaces based on convention:
            var conventionBasedMappings = new[]
            {
                "PayrollBureau.Data.Services",
                "PayrollBureau.Data.Interfaces",
                "PayrollBureau.Business.Services",
                "PayrollBureau.Business.Interfaces"
            };

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(tt => conventionBasedMappings.Any(n => n == tt.Namespace)),
                WithMappings.FromMatchingInterface,
                WithName.Default
                );

            container.RegisterType <IDocumentServiceRestClient, DocumentServiceRestClient>(
                new ContainerControlledLifetimeManager(),
                new InjectionConstructor(
                    new InjectionParameter <Uri>(new Uri(ConfigurationManager.AppSettings["DocumentRESTApiAddress"])),
                    new InjectionParameter <string>(ConfigurationManager.AppSettings["DocumentRESTUsername"]),
                    new InjectionParameter <string>(ConfigurationManager.AppSettings["DocumentRESTPassword"])
                    ));
        }
Exemple #29
0
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            container.RegisterType <IVeteranService, VeteranService>();
            container.RegisterType <IUserService, UserService>(new HierarchicalLifetimeManager());
            container.RegisterType <IImageVeteranService, ImageVeteranService>(new HierarchicalLifetimeManager());
            container.RegisterType <IArticleService, ArticleService>();
            container.RegisterType <IComment, ArticleService>("ArticleServiceComment");
            container.RegisterType <ICommentService, CommentService>(new HierarchicalLifetimeManager());
            container.RegisterType <IPhotoAlbumService, PhotoAlbumService>(new HierarchicalLifetimeManager());

            container.RegisterType <IDatabaseFactory, DatabaseFactory>(new HierarchicalLifetimeManager());
            container.RegisterType <IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType(typeof(IRepository <>), typeof(Repository <>));
            container.RegisterType <IImageService, ImageService>();
            container.RegisterType(typeof(IFormService <>), typeof(FormService <>));


            container.RegisterTypes(AllClasses.FromLoadedAssemblies().Where(t => t.BaseType == typeof(SpecificationBase <>)),
                                    WithMappings.FromMatchingInterface,
                                    WithName.Default);

            // TODO: Register your types here
            container.RegisterType <IUserStore <User>, UserStore <User> >();
            container.RegisterType <UserManager <User> >();
            container.RegisterType <User>();
            container.RegisterType <DbContext, ApplicationDbContext>();
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <AccountController>(new InjectionConstructor(typeof(ApplicationUserManager), typeof(IUserService)));

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            GlobalHost.DependencyResolver = new SignalRUnityDependencyResolver(container);

            container.RegisterType <CommentHub>(new InjectionFactory(CreateCommentHub));
        }
Exemple #30
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();


            // NOTE: Default lifetime manager is a Transient lifetime manager -
            // a new object every time one is needed


            container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromMatchingInterface, WithName.Default);


            container.RegisterType <ICodingTrainerRepository, SqlCodingTrainerRepository>();
            container.RegisterType <IIdeServices, IdeServices>();
            container.RegisterType <ICodeRunner, CodeRunner>();
            container.RegisterType <IExceptionLogger, CodeRunnerLogger>(new PerResolveLifetimeManager());
            container.RegisterType <IUserServices, UserServices>(new ContainerControlledLifetimeManager());

            // Controllers with more than one constructor, where
            // we want the one with fewer parameters to be used
            container.RegisterType <AccountController>(new InjectionConstructor());
            container.RegisterType <ManageController>(new InjectionConstructor(new Type[] { typeof(IUserServices) }));

            // Action Filters, etc aren't created using Unity's resolver, so we need to inject dependencies into them
            AuthorizeExerciseAttribute.UserServices   = container.Resolve <IUserServices>();
            AuthorizeExerciseAttribute.DbRepository   = container.Resolve <ICodingTrainerRepository>();
            AuthorizeSubmissionAttribute.UserServices = container.Resolve <IUserServices>();
            AuthorizeSubmissionAttribute.DbRepository = container.Resolve <ICodingTrainerRepository>();
            LogAndHandleErrorAttribute.Repository     = container.Resolve <ICodingTrainerRepository>();
            LogAndHandleWebApiError.Repository        = container.Resolve <ICodingTrainerRepository>();
        }