Пример #1
0
        private static void RegisterTypes(IUnityContainer container)
        {
            RegisterBitlyService(container);
            container.RegisterType <ILuceneService, LuceneRamService>();
            container.RegisterType <IUnitOfWork, UnitOfWork>();
            container.RegisterType <IUserRepository, UserRepository>();
            container.RegisterInstance <IDbSession>(new DbSession());

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath()
                .Where(t => t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEntityRepository <>))),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath()
                .Where(t => Attribute.IsDefined(t, typeof(BusinessLogicAttribute))),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            // Logging registered types.
            foreach (var item in container.Registrations)
            {
                Debug.WriteLine(item.RegisteredType + " - " + item.MappedToType + " - " + item.Name);
            }
        }
Пример #2
0
 private static void RegisterDependencies()
 {
     container.RegisterTypes(
         AllClasses.FromAssembliesInBasePath(),
         WithMappings.FromMatchingInterface,
         WithName.Default);
 }
Пример #3
0
        public static void Main(string[] args)
        {
            // Register
            var container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve);
            container.RegisterType <ILogger, ConsoleLogger>();

            // Resolve
            var sw = new Stopwatch();

            sw.Start();

            for (var i = 0; i < 100000; i++)
            {
                var application = container.Resolve <Application>();
            }

            sw.Stop();

            // Observe
            Console.WriteLine($"Unity - {sw.ElapsedMilliseconds}");
            Console.Read();
        }
Пример #4
0
 public static IUnityContainer ConfigureContainer(this IUnityContainer container)
 {
     return(container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath().Where(FilterTypes),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Transient));
 }
Пример #5
0
        public static void Initialize()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                (c) => WithMappings.FromMatchingInterface(c));
        }
Пример #6
0
 // Get the classes you want to register
 public override IEnumerable <Type> GetTypes()
 {
     // AllClasses.FromLoadedAssemblies() loads assemblies in the current app domain and is required for MVC project.
     // AllClasses.FromAssembliesInBasePath() loads assemblies from the bin directory and required so unit tests work.
     // AllClasses.FromAssembliesInBasePath() alone doesn't work for the MVC project because the base path of an MVC project isn't the bin directory
     return(AllClasses.FromLoadedAssemblies().Concat(AllClasses.FromAssembliesInBasePath())
            .Where(x => x.Assembly.FullName.Contains("UnityRegistrationByConvention.Services")));
 }
Пример #7
0
 public static IUnityContainer SetupEngine(this IUnityContainer container, Action <IEngineBuilder> build)
 {
     container.RegisterTypes(
         AllClasses.FromAssembliesInBasePath().Where(t => t.IsPublic && !t.IsAbstract && typeof(IHandlerBase).IsAssignableFrom(t)),
         WithMappings.None,
         WithName.Default,
         WithLifetime.Transient
         );
     return(SetupEngineScannerless(container, build));
 }
Пример #8
0
        public virtual void RegisterAllFromAssemblies(string name)
        {
            var container = _containersDictionary[RootContext];

            container?.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled);
        }
Пример #9
0
        /// <summary>
        /// Provides means to registry different service implementations
        /// based on the setup type
        /// </summary>
        public static void Bootstrap()
        {
            var container = new UnityContainer();

            var connection  = ConfigurationManager.ConnectionStrings["DatabaseConnection"]?.ConnectionString;
            var apiUrl      = ConfigurationManager.AppSettings["ApiUrl"];
            var resourceUrl = ConfigurationManager.AppSettings["ResourceUrl"];

            container.RegisterType <IConnection, Connection>(new InjectionConstructor(connection));
            container.RegisterType <IApiClient, ApiClient>(new InjectionConstructor(apiUrl, resourceUrl));

            container.RegisterType <ICatRepository, CatRepository>();
            container.RegisterType <IMessageBus, RabbitMessageBus>();
            container.RegisterType <ICatService, CatService>();
            container.RegisterType <IMainViewModel, MainViewModel>();

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.TypeName,
                WithLifetime.ContainerControlled,
                type =>
            {
                // If settings type, load the setting
                if (!type.IsAbstract && typeof(IConnection).IsAssignableFrom(type))
                {
                    return(new[]
                    {
                        new InjectionConstructor(connection)
                    });
                }

                // Otherwise, no special consideration is needed
                return(new InjectionMember[0]);
            });

            //container.RegisterTypes(
            //    AllClasses.FromAssemblies(),
            //    WithMappings.FromAllInterfaces,
            //    WithName.TypeName,
            //    WithLifetime.ContainerControlled
            //);
            //container.RegisterTypes(
            //    AllClasses.FromAssemblies(Assembly.GetExecutingAssembly()).Where(x =>
            //        x.IsPublic && x.GetInterfaces().Any() && (x.IsAbstract == false) &&
            //        x.IsClass), WithMappings.FromAllInterfacesInSameAssembly,
            //    type => container.Registrations.Select(x => x.RegisteredType)
            //        .Any(r => type.GetInterfaces().Contains(r))
            //        ? WithName.TypeName(type)
            //        : WithName.Default(type), WithLifetime.ContainerControlled);

            container.RegisterTypes(new InterfaceToTypeConvention(container, Assembly.GetExecutingAssembly()));

            IocWrapper.Instance = new IocWrapper(container);
        }
Пример #10
0
        private static IEnumerable <Type> GetClassesFromAssemblies(IEnumerable <Assembly> assemblies = null)
        {
            IEnumerable <Type> allClasses = assemblies != null
                ? AllClasses.FromAssemblies(assemblies)
                : AllClasses.FromAssembliesInBasePath();

            return
                (allClasses.Where(
                     n =>
                     n.Namespace != null));
        }
Пример #11
0
        static void AllClassesDemo()
        {
            Console.WriteLine("\n<<< AllClassesDemo >>>");
            Console.WriteLine("=============FromLoadedAssemblies");
            ShowClassesInfo(AllClasses.FromLoadedAssemblies().ToList());

            Console.WriteLine("=============FromAssembliesInBasePath");
            ShowClassesInfo(AllClasses.FromAssembliesInBasePath().ToList());

            Console.WriteLine("=============FromAssemblies");
            ShowClassesInfo(AllClasses.FromAssemblies().ToList());
        }
Пример #12
0
        private static void RegisterTypes(IUnityContainer container)
        {
            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            container.RegisterType <IEmailQueueRepository, EmailQueueRepository>();
            container.RegisterType <IEmailProcessorService, EmailProcessorService>();
            container.RegisterType <IEmailQueueServiceWs, EmailQueueServiceWs>();
            container.RegisterType <IScheduler>(new InjectionFactory(c => new StdSchedulerFactory().GetScheduler()));
        }
 /// <summary>
 /// Gets types to register.
 /// </summary>
 public override IEnumerable <Type> GetTypes()
 {
     // You may want to further restrict the search for classes to register
     // by doing some sort of namespace matching:
     //
     //     t.Namespace.StartsWith(
     //         "MyCompanyNamespacePrefix", StringComparison.Ordinal
     //     )
     //
     // for example.
     return(AllClasses.FromAssembliesInBasePath()
            .Where(t => t.Namespace.Contains("BusinessLogic.Services")));
 }
Пример #14
0
        public static IUnityContainer SetupEngine <TEnvironment>(this IUnityContainer container, Action <IEngineBuilder> build)
            where TEnvironment : class
        {
            var handlerTypes = AllClasses.FromAssembliesInBasePath().Where(t => !t.IsAbstract && typeof(IHandlerBase).IsAssignableFrom(t)).ToList();

            container.RegisterTypes(
                handlerTypes,
                WithMappings.None,
                WithName.Default,
                WithLifetime.Transient
                );
            return(SetupEngineScannerless <TEnvironment>(container, build));
        }
 public void GettingTypesFromAssembliesLoadedFromBaseFolderWithErrorsThrows()
 {
     try
     {
         var types = AllClasses.FromAssembliesInBasePath(skipOnError: false).ToArray();
     }
     catch (Exception e)
     {
         if (e is AssertFailedException)
         {
             throw;
         }
     }
 }
Пример #16
0
        private static Implementation.BookProcessor CompositionByConvention()
        {
            // Composition using unity DI container.
            using (var container = new UnityContainer())
            {
                container.RegisterTypes(
                    AllClasses.FromAssembliesInBasePath(),
                    WithMappings.FromAllInterfaces,
                    WithName.Default,
                    WithLifetime.Transient);

                return(container.Resolve <Implementation.BookProcessor>());
            }
        }
        public void GetsTypesFromAssembliesLoadedFromBaseFolderExcludingSystemAndUnityByDefault()
        {
            if (!File.Exists("NotReferencedTestNetAssembly.dll"))
            {
                Assert.Inconclusive("The assembly was not found. Run this test without deployment");
            }

            var typesByAssembly = AllClasses.FromAssembliesInBasePath().GroupBy(t => t.Assembly).ToDictionary(g => g.Key);

            Assert.IsFalse(typesByAssembly.ContainsKey(typeof(Uri).Assembly));
            Assert.IsFalse(typesByAssembly.ContainsKey(typeof(IUnityContainer).Assembly));
            Assert.IsTrue(typesByAssembly.Any(g => g.Key.GetName().Name == "NotReferencedTestNetAssembly"), "No types for NotReferencedTestNetAssembly");
            Assert.IsTrue(typesByAssembly.ContainsKey(typeof(Microsoft.Practices.Unity.Tests.TestNetAssembly.PublicClass1).Assembly), "No types for TestNetAssembly");
        }
Пример #18
0
        protected override void Configure()
        {
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) == false)
            {
                _container.RegisterTypes(
                    AllClasses.FromAssembliesInBasePath(),
                    WithMappings.FromMatchingInterface,
                    WithName.Default,
                    WithLifetime.Transient);

                Singleton <IWindowManager, WindowManager>();
                Singleton <IEventAggregator, EventAggregator>();
                Singleton <ISettings, Settings>();
            }
        }
Пример #19
0
        public void WhenSomeTypesCannotBeLoadedAndSkipFlagIsFalse()
        {
            IUnityContainer container = new UnityContainer();

            AssertHelper.ThrowsException <DuplicateTypeMappingException>(() =>
            {
                return(container.RegisterTypes(
                           AllClasses.FromAssembliesInBasePath(false, false),
                           WithMappings.FromAllInterfaces,
                           WithName.TypeName,
                           null,
                           null,
                           false));
            });
        }
Пример #20
0
        public IController GetController(Route route)
        {
            if (!_controllers.TryGetValue(route.Controller, out Type controllerType))
            {
                var potentialControllerName = route.Controller + "Controller";
                controllerType = AllClasses.FromAssembliesInBasePath().FirstOrDefault(t => t.Name == potentialControllerName);

                //controllerType = CurrentAssembly.GetType($"{ControllerPrefix}.{route.Controller}Controller");
                _controllers.Add(route.Controller, controllerType);
            }

            return(controllerType == null
                ? null
                : (IController)_currentContainer.CreateChildContainer().Resolve(controllerType));
        }
Пример #21
0
        internal void ConfigureContainer(RDomCorporation corporation)
        {
            var types = AllClasses.FromAssembliesInBasePath()
                        .Where(x => x.Namespace != null &&
                               x.Namespace.StartsWith("RoslynDom"));

            // TODO: *** Load other things, at least SameIntent and IWorker
            LoadIntoContainerWithArgument <IRDomFactory, RDomCorporation>(types, corporation);
            LoadIntoContainerWithArgument <IRDomCompilationFactory, RDomCorporation>(types, corporation);
            LoadIntoContainer <IContainerCheck>(types);
            LoadIntoContainer <IWorker>(types);
            //LoadIntoContainerWithArgument<ICreateFromWorker, RDomCorporation>(types, corporation);
            //LoadIntoContainerWithArgument<IBuildSyntaxWorker, RDomCorporation>(types, corporation);
            LoadIntoContainer <ISameIntent>(types);
            isLoaded = true;
        }
Пример #22
0
        private void OnApplicationStartup(object sender, StartupEventArgs e)
        {
            CreateMappings();

            container = new UnityContainer();
            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.Default
                );

            MainWindow = container.Resolve <TaskListView>();
            MainWindow.Show();

            ((TaskListController)MainWindow.DataContext).OnLoad();
        }
Пример #23
0
        private void OnApplicationStartup(object sender, StartupEventArgs e)
        {
            CreateMappings();

            container = new UnityContainer();
            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath().Where(type => type.Assembly.FullName.StartsWith(MatchingAssemblyPrefix)),
                UserDefinedInterfaces,
                WithName.Default
                );

            MainWindow = container.Resolve <TaskListView>();
            MainWindow.Show();

            ((TaskListController)MainWindow.DataContext).OnLoad();
        }
Пример #24
0
        public static void RegisterComponents()
        {
            Container  = new UnityContainer();
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.RollingFile("log-{Date}.txt")
                         .WriteTo.ColoredConsole().CreateLogger();



            Container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath().Where(x => x.GetInterfaces().Contains(typeof(ISingletonDependency))),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled
                );
        }
Пример #25
0
        public void WhenSomeTypesCannotBeLoadedAndSkipFlagIsTrue()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(false, false, true),
                WithMappings.FromAllInterfaces,
                WithName.TypeName,
                null,
                null,
                true);

            var resolved1 = container.Resolve <IInterface3>("TypeImplementingI3");
            var resolved2 = container.Resolve <ITypeImplementingI1>("TypeToRegisterInDifferentAssembly");

            Assert.IsInstanceOfType(resolved1, typeof(TypeImplementingI3));
            Assert.IsInstanceOfType(resolved2, typeof(TypeToRegisterInDifferentAssembly));
        }
Пример #26
0
        private static void Main(string[] args)
        {
            using (var container = new UnityContainer())
            {
                // Manual method.
                //container.RegisterType<IEntryPoint, EntryPoint>();
                //container.RegisterType<IInjected, Injected>();

                // http://blogs.msdn.com/b/agile/archive/2013/03/12/unity-configuration-registration-by-convention.aspx
                container.RegisterTypes(
                    AllClasses.FromAssembliesInBasePath(),
                    WithMappings.FromMatchingInterface,
                    WithName.Default,
                    WithLifetime.ContainerControlled);

                var controller = container.Resolve <IEntryPoint>();
                controller.Main();
            }
        }
Пример #27
0
        private static IUnityContainer BuildUnityContainer()
        {
            // register all your components with the container here
            //This is the important line to edit
            //var container = new UnityContainer();
            // container.RegisterType<ICompanyRepository, CompanyRepository>();

            using (var container = new UnityContainer())
            {
                //var currentAssembly = Assembly.LoadFrom(assembly);

                container.RegisterTypes(
                    AllClasses.FromAssembliesInBasePath(),
                    WithMappings.FromMatchingInterface,
                    WithName.Default,
                    WithLifetime.ContainerControlled);

                RegisterTypes(container);
                return(container);
            }
        }
Пример #28
0
        private static void ConfigureContainer()
        {
            cContainer.RegisterInstance(typeof(IsolationLevel), IsolationLevel.ReadCommitted)
            .RegisterPerResolve <IScheduleChecker, ScheduleChecker>()
            .RegisterPerResolve <IRssReader, RawXmlRssReader>()
            .RegisterPerResolve <IControllerFactory, ControllerFactory>()
            .RegisterPerResolve <IUnitOfWork, EFUnitOfWork>()
            .RegisterPerResolve <IDbContextFactory, DigitalSignageDbContextFactory>(new InjectionConstructor("DigitalSignageLocalDB"))
            .RegisterType(typeof(IRepository <>), typeof(EFRepository <>), new PerResolveLifetimeManager())
            .RegisterInstance <IPersistenceFactory>(cContainer.Resolve <EFPersistenceFactory>());

            cContainer.RegisterTypes(
                AllClasses.FromAssembliesInBasePath().Where(t => t.Namespace.Contains("BusinessLogic.Services")),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.PerResolve
                );

            cContainer.RegisterType <IDbContext>(
                new PerResolveLifetimeManager(),
                new InjectionFactory(c => c.Resolve <IDbContextFactory>().CreateContext())
                );
        }
Пример #29
0
        private static IEnumerable <Type> GetClassesFromAssemblies(IEnumerable <Assembly> assemblies = null)
        {
            var allClasses = assemblies != null?AllClasses.FromAssemblies(assemblies) : AllClasses.FromAssembliesInBasePath();

            return
                (allClasses.Where(
                     n =>
                     n.Namespace != null &&
                     n.Namespace.StartsWith(ApplicationNamespace, StringComparison.InvariantCultureIgnoreCase)));
        }
Пример #30
0
        private static void RegisterTypes(IUnityContainer container)
        {
            string basePath = AppDomain.CurrentDomain.RelativeSearchPath
                              ?? AppDomain.CurrentDomain.BaseDirectory;
            List <Assembly> allAssemblies = new List <Assembly>();

            //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            foreach (string dll in Directory.GetFiles(basePath, "Spooler.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "BL.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "Common.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "Urf.Repository.Pattern.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "DAL.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "Printing_CP500.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }
            foreach (string dll in Directory.GetFiles(basePath, "VOSTOKDataSource.dll"))
            {
                allAssemblies.Add(Assembly.LoadFrom(dll));
            }

            container.RegisterInstance <ILog>(log, new ContainerControlledLifetimeManager());
            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath().WithMatchingInterface() // for all assemblies
                //AllClasses.FromLoadedAssemblies().WithMatchingInterface() // for all assemblies
                //AllClasses.FromAssemblies(allAssemblies).WithMatchingInterface() // for specified only
                , WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.Transient,

                c => new InjectionMember[]
            {
                new  Interceptor <InterfaceInterceptor>()
                ,
                new InterceptionBehavior <ProfilingInterceptionBehavior>()
            }
                //null
                , true);


            //container.RegisterType<IVostok_Helper, Vostok_Helper>(new TransientLifetimeManager());
            //container.RegisterType<IAppSettings, AppSettings>(new TransientLifetimeManager());
            //container.RegisterType<Itest, test>(new TransientLifetimeManager(), new Interceptor<InterfaceInterceptor>(),
            //new InterceptionBehavior<ProfilingInterceptionBehavior>());

            common.infrastructure.UnityRegister.Register(container);
            BL.infrastructure.UnityRegister.Register(container);
            //Itest t = container.Resolve<Itest>();
            //t.write();
        }