Example #1
0
        private static IMediator BuildMediator()
        {
            var container = new UnityContainer();
            container.RegisterTypes(AllClasses.FromAssemblies(typeof (Ping).Assembly), WithMappings.FromAllInterfaces);
            container.RegisterTypes(AllClasses.FromAssemblies(typeof (IMediator).Assembly), WithMappings.FromAllInterfaces);
            container.RegisterInstance(Console.Out);

            var serviceLocator = new UnityServiceLocator(container);
            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);
            container.RegisterInstance(serviceLocatorProvider);

            var mediator = container.Resolve<IMediator>();

            return mediator;
        }
Example #2
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 UnityTests()
        {
            var container = new UnityContainer();
            container.RegisterTypes(AllClasses.FromAssemblies(typeof(A).Assembly), WithMappings.FromAllInterfaces, overwriteExistingMappings: true);

            ServiceLocator = new UnityServiceLocator(container);
        }
Example #4
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));
        }
        public static IUnityContainer CreateUnityContainer()
        {
            var container = new UnityContainer();
            container.RegisterType<IMediator, Mediator>();
            var types = AllClasses.FromAssemblies( typeof( Program ).Assembly );

            container.RegisterTypes(
                types,
                WithMappings.FromAllInterfaces,
                GetName,
                GetLifetimeManager,
                null,
                true );

            container.RegisterInstance<SingleInstanceFactory>( t =>
             {
                 var pipeline = container.Resolve(
                     typeof( MediatorPipeline<,> ).MakeGenericType( t.GetGenericArguments() )
                 );

                 return pipeline;

             } );
            container.RegisterInstance<MultiInstanceFactory>( t => container.ResolveAll( t ) );

            return container;
        }
        public static void RegisterComponents()
        {
			var container = new UnityContainer();

            var applicationDataAssembly = AppDomain.CurrentDomain.GetAssemblies()
                .First(a => a.FullName == "Application.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

            container.RegisterType<ApplicationDbContext>(new PerResolveLifetimeManager());

            container.RegisterTypes(applicationDataAssembly.GetTypes(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            container.RegisterType<IAuthenticationManager>(
                new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

            container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                new InjectionConstructor(typeof(ApplicationDbContext)));


            container.RegisterType<IRoleStore<ApplicationRole, string>, RoleStore<ApplicationRole, string, IdentityUserRole>>(
                new InjectionConstructor(typeof(ApplicationDbContext)));
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
Example #7
0
      private static IUnityContainer ConfigureContainer(IServiceProvider package, ServiceLocatorOptions options)
      {
         if (package == null)
            throw new ArgumentNullException(nameof(package), $"{nameof(package)} is null.");

         IUnityContainer container = new UnityContainer();
         container.AddExtension(new ServiceProviderUnityExtension(package, options));

         container.RegisterType<IToolkit, TookitImpl>(new ContainerControlledLifetimeManager());
         container.RegisterTypes(new SolutionExplorerNodeFactoryRegistrationConvention());
         container.RegisterType<IEnumerable<ISolutionExplorerNodeFactory>, ISolutionExplorerNodeFactory[]>();
         container.RegisterType<ISolutionExplorerNodeFactory, GlobalSolutionExplorerNodeFactory>();

         container.RegisterType<ISolutionExplorer, SolutionExplorer>();
         container.RegisterType<IOutputWindow, OutputWindow>(new ContainerControlledLifetimeManager());
         container.RegisterType<IDialogService, DialogService>(new ContainerControlledLifetimeManager());

         container.RegisterType<IEnumerable<ICommandImplementation>, ICommandImplementation[]>();

         container.RegisterInstance<IServiceProvider>(package);

         container.RegisterType<ICommandManager, CommandManager>(new ContainerControlledLifetimeManager());

         UnityServiceLocator serviceLocator = new UnityServiceLocator(container);
         container.RegisterInstance<IServiceLocator>(serviceLocator);

         if (!ServiceLocator.IsLocationProviderSet)
            ServiceLocator.SetLocatorProvider(() => serviceLocator);

         return container;
      }
Example #8
0
        public static void RegisterComponents(HttpConfiguration configuration)
        {
            // create a Unity container
            var container = new UnityContainer();

            // create an AutoMapper configuration
            var mapperConfiguration = DtoMapperConfiguration.Build();

            // register dependencies by convention
            // this will register all classes with matching interfaces in loaded assemblies (in a real world app you might want to be more explicit on assemblies to scan)
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            // register a dependency, in this case a mapping from the greeting repository interface to the greeting repository implementation
            // convention based registraton above will have already done this, shown explicitly here for demo purposes
            container.RegisterType<IGreetingRepository, GreetingRepository>();

            // here we are registering AutoMapper and controlling how Unity creates the instance by specifying an injection factory
            container.RegisterType<IMapper>("dtoMapper", new InjectionFactory(x => mapperConfiguration.CreateMapper()));

            // Web API has built in support for dependency injection by setting the DependencyResolver property on the configuration object
            // here we register the Unity container with Web API as a dependency resolver
            configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
Example #9
0
 internal static void Configure(UnityContainer container)
 {
     container.RegisterTypes
                 (FromTypes(),
                 FromMachingInterfaces,
                 WithName.Default,
                 WithLifetime.ContainerControlled);
 }
        private static void RegisterUnityContainer(HttpConfiguration config)
        {
            var container = new UnityContainer();
            container.RegisterTypes(AllClasses.FromLoadedAssemblies(), WithMappings.FromAllInterfaces, WithName.TypeName, WithLifetime.Transient);
            config.DependencyResolver = new UnityResolver(container);

            //config.Filters.Add(new UnhandledExceptionFilter());
        }
Example #11
0
 public static UnityContainer RegisterTypes()
 {
     var container = new UnityContainer();
     container.RegisterTypes(AllClasses.FromAssemblies(true, LoadAssemblies()),
                             WithMappings.FromMatchingInterface,
                             WithName.Default,
                             PerRequest);
     return container;
 }
        public void WhenRegisteringFromLoadedTypes()
        {
            IUnityContainer container = new UnityContainer();

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

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

                Assert.IsFalse(registration.Name.Contains("TypeInAssemblyToLoad"));
            }

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

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

                if (registration.Name.Contains("TypeInAssemblyToLoad"))
                {
                    found = true;
                }
            }

            Assert.IsTrue(found);
        }
Example #13
0
        public static void RegisterComponents()
        {
			var container = new UnityContainer();
            var allClasses = AllClasses.FromAssemblies(BuildManager.GetReferencedAssemblies().Cast<Assembly>());
            
            container.RegisterTypes(allClasses, WithMappings.FromMatchingInterface, WithName.Default);
            container.AddNewExtension<MapsContainerExtension>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
Example #14
0
        public static IUnityContainer RegisterComponents()
        {
            var container = new UnityContainer();

            // Register all repository classes automatically
            // Register all service classes automatically in the business layer

            container.RegisterTypes(
                AllClasses.FromAssemblies(new[]
                {
                    Assembly.Load("Neemo"),
                    Assembly.Load("Neemo.CarParts"),
                    Assembly.Load("Neemo.CarParts.EntityFramework"),
                }),
                WithMappings.FromMatchingInterface,
                WithName.Default);

            // Register ilogger with log4net
            container.RegisterType<ILogger, Log4NetLog>();

            // Register the PayPal payment service ( later we may have a few more :)
            container.RegisterType<Payments.IPaymentService, Payments.pp.PaymentService>();

            // FileStore image service requires http utility to initialise
            container.RegisterType<Images.IImageService, Images.FileImageService>(new InjectionConstructor(HttpContext.Current.Server.MapPath("~/"), typeof(ISysConfig)));

            // ICartContext (session based)
            container.RegisterType<ShoppingCart.ICartContext, Infrastructure.SessionCartContext>();

            // Services in website/infrastructure ( including the local mapping config )
            container.RegisterType<Infrastructure.ITemplateService, Infrastructure.TemplateService>();
            container.RegisterType<Shipping.IShippingCalculatorService, Infrastructure.ShippingService>();

            // Register all the assemblies that use the IMapping Config
            container.RegisterType<IMappingConfig, MappingConfig>("WebConfig");
            container.RegisterTypes(new RegisterMappersConvention("Neemo.CarParts.EntityFramework", "Neemo.Payments.PayPal"));

            // Set the MVC dependency resolver to use Unity!
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            return container;
        }
        public void WhenRegisteringMappedInterfacesFromAnAssemblyWithTypeNamesInterfaceRegistrationNameIsNotMismatched2()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromAssemblies(Assembly.Load(new AssemblyName(RegistrationByConventionAssembly1Name))),
                WithMappings.FromAllInterfacesInSameAssembly,
                WithName.TypeName,
                null);

            AssertHelper.ThrowsException<ResolutionFailedException>(() => container.Resolve<IInterface2>("TypeImplementingI1"));
        }
Example #16
0
        internal static IUnityContainer BuildMediator()
        {
            var container = new UnityContainer();
            container.RegisterType<IMediator, Mediator>();
            container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly), WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);
            container.RegisterType(typeof(INotificationHandler<>), typeof(GenericHandler), GetName(typeof(GenericHandler)));
            container.RegisterType(typeof(IAsyncNotificationHandler<>), typeof(GenericAsyncHandler), GetName(typeof(GenericAsyncHandler)));
            container.RegisterInstance(Console.Out);
            container.RegisterInstance<SingleInstanceFactory>(t => container.Resolve(t));
            container.RegisterInstance<MultiInstanceFactory>(t => container.ResolveAll(t));

            return container;
        }
        public IDependencyResolver Register()
        {
            var container = new UnityContainer();

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

            container.RegisterType<ICompanyQuery, CompanyQuery>(new ContainerControlledLifetimeManager());

            return new UnityDependencyResolver(container);
        }
Example #18
0
        public void InitializeDependencies()
        {
            var IoCcontainer = new UnityContainer();

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

            IoCcontainer.LoadConfiguration();

            //Gets the resolution root
            commandHandler = IoCcontainer.Resolve<ICommandHandler>();
        }
Example #19
0
 public static void Register(HttpConfiguration config)
 {
     var unityContainer = new UnityContainer();
     unityContainer.RegisterInstance<DataService>(new DataService());
     unityContainer.RegisterTypes(
         AllClasses.FromLoadedAssemblies().Where(t => t.IsAssignableFrom(typeof(IHttpController))),
         WithMappings.FromAllInterfaces);
     config.DependencyResolver = new UnityDependencyResolver(unityContainer);
   
     config.MapHttpAttributeRoutes();
     config.Services.Replace(typeof(IExceptionHandler),new GlobalErrorHandlerService());
     config.MessageHandlers.Add(new ErrorHandlerMessageHandler());
     config.MessageHandlers.Add(new BufferNonStreamedContentHandler());
     config.EnableSystemDiagnosticsTracing();
 }
        public static void Resolve(UnityContainer container)
        {
            // Mapeamento padrão para todas as interfaces e implementações
            // que seguem o padrão INomeConcreto/NomeConcreto
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Transient);

            // Entidades que não possuem o mesmo nome da interface apenas acrescentando o I como prefixo
            // Ex.: PedidoRepositoryEf implementa a interface IPedidoRepository
            container.RegisterType<IPedidoRepository, PedidoRepositoryEf>();
            container.RegisterType<IItemPedidoRepository, ItemPedidoRepositoryEf>();
        }
        public static IUnityContainer GetContainer()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterTypes(
                AllClasses.FromAssembliesInBasePath(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.ContainerControlled,
                overwriteExistingMappings:true);

            // Manual Mappings
            container.RegisterType<IConversationRepository, Data.EntityFramework.Conversations.ConversationRepository>();
            
            return container;
        }
        public void WhenSomeTypesCannotBeLoadedAndSkipFlagIsFalse()
        {
            IUnityContainer container = new UnityContainer();

            AssertHelper.ThrowsException<DuplicateTypeMappingException>(() =>
            {
                return container.RegisterTypes(
                    AllClasses.FromAssembliesInBasePath(false, false),
                    WithMappings.FromAllInterfaces,
                    WithName.TypeName,
                    null,
                    null,
                    false);
            });
        }
        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();
        }
Example #24
0
        public static IUnityContainer RegisterComponents(HttpConfiguration config)
        {
            var container = new UnityContainer();

            //container.RegisterType<IAuthentication, Authentication>();
            //container.RegisterType<IArticleManager, ArticleManager>();
            //container.RegisterType<IArticleRepository, ArticleRepository>();
            //container.RegisterType<INewsPortalContext, NewsPortalContext>();
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.None);
            config.DependencyResolver = new UnityDependencyResolver(container);
            return container;
        }
Example #25
0
        private static UnityContainer RegisterUnityRootContainer()
        {
            var container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Hierarchical);
            
            container.RegisterType<IRepository, EntityRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IAccountService, AccountService>(new HierarchicalLifetimeManager());
            container.RegisterType<IWidgetService, WidgetService>(new HierarchicalLifetimeManager());

            return container;
        }
        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();
        }
Example #27
0
        public static void RegisterComponents()
        {
            Container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers

            Container
                .RegisterType<IUnitOfWork, UnitOfWork>();

            Container.RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default,
                WithLifetime.Hierarchical);
            
            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(Container);
        }
        public void WhenMultipleMappingsToSameInterfaceLastOneWinsWins()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(
                AllClasses.FromAssemblies(Assembly.Load(new AssemblyName(RegistrationByConventionAssembly1Name))),
                WithMappings.FromAllInterfacesInSameAssembly,
                WithName.Default,
                null,
                null,
                true);

            var resolved1 = container.Resolve<ITypeImplementingI1>();
            var resolved2 = container.Resolve<IInterface2>();

            Assert.IsInstanceOfType(resolved1, typeof(TypeImplementingI12));
            Assert.IsInstanceOfType(resolved2, typeof(TypeImplementingI12));
        }
Example #29
0
        private static IUnityContainer BuildUnityContainer()
        {

            UnityContainer container = new UnityContainer();
            container.RegisterTypes(
                AllClasses.FromLoadedAssemblies().Where(t => t.Namespace != null && t.Namespace.Contains("CSN.Business")),
                         WithMappings.FromMatchingInterface,
                        WithName.Default //,
                //WithLifetime.ContainerControlled
                        );


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

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

            return container;
        }
        public void CanResolveMappedInterfacesFromAnAssemblyWithTypeNames()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterTypes(AllClasses.FromAssemblies(Assembly.Load(new AssemblyName(RegistrationByConventionAssembly1Name))),
                WithMappings.FromAllInterfacesInSameAssembly,
                WithName.TypeName,
                null);

            var resolved1 = container.Resolve<ITypeImplementingI1>("TypeImplementingI1");
            var resolved2 = container.Resolve<IInterface2>("TypeImplementingI2");
            var resolved3 = container.Resolve<ITypeImplementingI1>("TypeImplementingI12");
            var resolved4 = container.Resolve<IInterface2>("TypeImplementingI12");

            Assert.IsInstanceOfType(resolved1, typeof(TypeImplementingI1));
            Assert.IsInstanceOfType(resolved2, typeof(TypeImplementingI2));
            Assert.IsInstanceOfType(resolved3, typeof(TypeImplementingI12));
            Assert.IsInstanceOfType(resolved4, typeof(TypeImplementingI12));
        }