Ejemplo n.º 1
0
        private static void CheckIfRegistered(UnityContainer unityContainer)
        {
            log4net.Config.XmlConfigurator.Configure();
            var log = log4net.LogManager.GetLogger(typeof(Program));

            log.Info("Checking if manager and plugins are registered");
            if (!unityContainer.IsRegistered <ITransferManager>(_transferManager))
            {
                log.Error("Given transfer manager isn't registered");
                log.Info(GetHelp());
                throw new InvalidPluginException("Given Transfer Manager isn't registered.");
            }
            if (!unityContainer.IsRegistered <IInputPlugin>(_inputPlugin))
            {
                log.Error("Given Input Plugin isn't registered");
                log.Info(GetHelp());
                throw new InvalidPluginException("Given Input Plugin isn't registered.");
            }
            if (!unityContainer.IsRegistered <IOutputPlugin>(_outputPlugin))
            {
                log.Error("Given Output Plugin isn't registered");
                log.Info(GetHelp());
                throw new InvalidPluginException("Given Output Plugin isn't registered.");
            }
            log.Info("Manager and plugins are registered");
        }
Ejemplo n.º 2
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            //Dependency injection with unity container
            var container = new UnityContainer();

            if (!container.IsRegistered <IUserRepository>())
            {
                container.RegisterType <IUserRepository, UserRepository>();
            }
            if (!container.IsRegistered <ICommentRepository>())
            {
                container.RegisterType <ICommentRepository, CommentRepository>();
            }
            if (!container.IsRegistered <ICategoryRepository>())
            {
                container.RegisterType <ICategoryRepository, CategoryRepository>();
            }
            if (!container.IsRegistered <IBookRepository>())
            {
                container.RegisterType <IBookRepository, BookRepository>();
            }
            if (!container.IsRegistered <IMovieRepository>())
            {
                container.RegisterType <IMovieRepository, MovieRepository>();
            }

            if (!container.IsRegistered <IUserService>())
            {
                container.RegisterType <IUserService, UserService>();
            }
            if (!container.IsRegistered <ICommentService>())
            {
                container.RegisterType <ICommentService, CommentService>();
            }
            if (!container.IsRegistered <ICategoryService>())
            {
                container.RegisterType <ICategoryService, CategoryService>();
            }
            if (!container.IsRegistered <IBookService>())
            {
                container.RegisterType <IBookService, BookService>();
            }
            if (!container.IsRegistered <IMovieService>())
            {
                container.RegisterType <IMovieService, MovieService>();
            }

            config.DependencyResolver = new UnityResolver(container);
        }
Ejemplo n.º 3
0
        public TService GetInstance <TService>() where TService : class
        {
            if (_container.IsRegistered <TService>())
            {
                _container.RegisterType <TService>();
            }

            return(_container.Resolve <TService>());
        }
Ejemplo n.º 4
0
        public void RegisterType_Valid()
        {
            var helper = new UnityHelper();

            var container = new UnityContainer();

            Assert.IsFalse(container.IsRegistered(typeof(ITestInterface)));

            helper.RegisterType(container, typeof(ITestInterface), typeof(TestClass1), RegistrationType.Singleton);
            Assert.IsTrue(container.IsRegistered(typeof(ITestInterface)));
        }
Ejemplo n.º 5
0
        public void RegisterDependencies()
        {
            IUnityContainer container = new UnityContainer();

            MockStartupController controller = new MockStartupController(container);

            controller.CallRegisterDependencies();

            Assert.That(container.IsRegistered <IStartupView>(), Is.True);
            Assert.That(container.IsRegistered <IMainView>(), Is.True);
        }
Ejemplo n.º 6
0
        public void Run <TPresenter>() where TPresenter : class, IPresenter
        {
            if (!_container.IsRegistered <TPresenter>())
            {
                _container.RegisterType(typeof(TPresenter));
            }

            var presenter = _container.Resolve <TPresenter>();

            presenter.Run();
        }
Ejemplo n.º 7
0
        //REGISTER
        //Register interface to class
        public void Register <T, TT>(IoCLifeTimeType ltt) where TT : class, T
        {
            var ltm = getLifeTimeManager(ltt);

            if (!Container.IsRegistered <T>())
            {
                Container.RegisterType <T, TT>(ltm).Configure <Interception>().SetInterceptorFor <T>(new InterfaceInterceptor());
            }
            //else  throw new Exception("Already registered.");
        }
Ejemplo n.º 8
0
        public void RegisterInstance_Valid()
        {
            var helper   = new UnityHelper();
            var instance = new TestClass1()
            {
                Name = "test"
            };

            var container = new UnityContainer();

            Assert.IsFalse(container.IsRegistered(typeof(ITestInterface)));

            helper.RegisterInstance(container, typeof(ITestInterface), instance);
            Assert.IsTrue(container.IsRegistered(typeof(ITestInterface)));
            Assert.AreEqual(instance, container.Resolve <ITestInterface>());
        }
Ejemplo n.º 9
0
        public Object Get(Type type)
        {
            if (!_container.IsRegistered(type))
            {
                var interfaces = type.GetInterfaces();

                if (interfaces.Length == 1 && _container.IsRegistered(interfaces[0]))
                {
                    var instance = _container.Resolve(interfaces[0]);
                    _container.RegisterInstance(type, instance);
                    return(instance);
                }
            }

            return(_container.Resolve(type));
        }
Ejemplo n.º 10
0
        static MessageService()
        {
            if (!MessagingEnabled)
            {
                return;
            }

            var unitySection = ConfigurationManager.GetSection("unity");

            if (unitySection == null)
            {
                log.Error("Required unity configuration for Message Sender");
                return;
            }

            try
            {
                var unity = new UnityContainer().LoadConfiguration(unityContainerName);
                if (unity.IsRegistered <IMessageSender>())
                {
                    sender = unity.Resolve <IMessageSender>();
                }
                else
                {
                    log.Error("Required unity configuration for Message Sender");
                }
            }
            catch (Exception ex)
            {
                log.Error("Error while resolving Message Sender: " + ex);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates and initializes an instance of type T
        /// </summary>
        /// <typeparam name="T">Type of service to initialize</typeparam>
        /// <returns>Instance of the service created</returns>
        public static T Resolve <T>()
        {
            bool isRegistered;

            lock (UnityContainer)
            {
                isRegistered = UnityContainer.IsRegistered <T>();
            }

            if (!isRegistered)
            {
                CountdownEvent latch = new CountdownEvent(1);
                Latches.TryAdd(typeof(T), latch);
                latch.Wait();
            }

            T ret;

            lock (UnityContainer)
            {
                ret = UnityContainer.Resolve <T>();
            }

            return(ret);
        }
Ejemplo n.º 12
0
        private static void Initialize()
        {
            var container = new UnityContainer();

            container.RegisterInstance <IMessageRouter>(new MessageRouter());

            HttpServiceLocator.Namespaces = new string[] { "WebApiDemo.PlugIn.Models" };
            HttpServiceLocator.DefaultInstance.GetHttpClient = p => new HttpClient()
            {
                BaseAddress = new Uri("http://localhost:54619/PersonModule/")
            };
            HttpServiceLocator.DefaultInstance.GetValues     = p => container.ResolveAll(p).ToArray();
            HttpServiceLocator.DefaultInstance.RegisterValue = (x, y, z) => container.RegisterInstance(x, y, z);
            HttpServiceLocator.DefaultInstance.TryGetValue   = delegate(Type serviceType, string name, out object value)
            {
                value = null;
                if (container.IsRegistered(serviceType, name))
                {
                    value = container.Resolve(serviceType, name);
                    return(true);
                }

                return(false);
            };

            ServiceLocator.SetLocatorProvider(() => HttpServiceLocator.DefaultInstance);
        }
Ejemplo n.º 13
0
 public override object GetService(Type serviceType)
 {
     if (_container.IsRegistered(serviceType))
     {
         return(_container.Resolve(serviceType));
     }
     return(base.GetService(serviceType));
 }
Ejemplo n.º 14
0
 private static void ConfigureCoreContextByUnity(object section)
 {
     if (((UnityConfigurationSection)section).Containers["Core"] != null)
     {
         var unity = new UnityContainer().LoadConfiguration("Core");
         if (unity.IsRegistered <IConfigurationClient>())
         {
             Configuration = unity.Resolve <IConfigurationClient>();
         }
         if (unity.IsRegistered <ITenantManagerClient>())
         {
             TenantManager = unity.Resolve <ITenantManagerClient>();
         }
         if (unity.IsRegistered <IUserManagerClient>())
         {
             UserManager = unity.Resolve <IUserManagerClient>();
         }
         if (unity.IsRegistered <IGroupManagerClient>())
         {
             GroupManager = unity.Resolve <IGroupManagerClient>();
         }
         if (unity.IsRegistered <IAuthManagerClient>())
         {
             Authentication = unity.Resolve <IAuthManagerClient>();
         }
         if (unity.IsRegistered <IAzManagerClient>())
         {
             AuthorizationManager = unity.Resolve <IAzManagerClient>();
         }
         if (unity.IsRegistered <ISubscriptionManagerClient>())
         {
             SubscriptionManager = unity.Resolve <ISubscriptionManagerClient>();
         }
     }
 }
Ejemplo n.º 15
0
        private object Resolve(Resolution resolution)
        {
            var type = resolution.Key as Type;

            // Unity will create objects even if not registered
            return(type != null && _container.IsRegistered(type)
                 ? ((IContainer)this).Resolve(resolution.Key)
                 : null);
        }
Ejemplo n.º 16
0
        private TIUser PrivateGetUser(string userName)
        {
            if (!_unityContainer.IsRegistered <TIUser>(userName))
            {
                throw new TestActionsException(string.Format("Пользователь \"{0}\" незарегистрирован.", userName));
            }

            return(_unityContainer.Resolve <TIUser>(userName));
        }
Ejemplo n.º 17
0
        static CalculateOtFactory()
        {
            IUnityContainer container = new UnityContainer().LoadConfiguration();

            if (container.IsRegistered <ICalculate>("CalOtPay"))
            {
                CalOtPay = container.Resolve <ICalculate>("CalOtPay");
            }
        }
Ejemplo n.º 18
0
        public void IsRegisteredReturnsCorrectValue()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterType <MyClass>(new InjectionConstructor("Name"));
            var inst = container.Resolve <MyClass>();

            Assert.IsTrue(container.IsRegistered <MyClass>());
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Обеспечивает проверку на возможность решения типа.
        /// </summary>
        /// <typeparam name="T">Тип для резолвинга.</typeparam>
        /// <returns>Инициализированный объект типа или null.</returns>
        private T SaveResolve <T>() where T : class
        {
            T result = null;

            if (_container.IsRegistered <T>())
            {
                result = _container.Resolve <T>();
            } //if

            return(result);
        }
        public void UnityIsRegistered()
        {
            UnityContainer c = new UnityContainer();

            c.RegisterInstance <IServiceScopeFactory>(new UnityServiceScopeFactory(c));
            var sp = new UnityServiceProvider(c);

            c.RegisterInstance <IServiceProvider>(sp);
            c.RegisterSingleton <IFoo, Foo>();

            c.IsRegistered(typeof(IFoo)).Should().BeTrue();
        }
Ejemplo n.º 21
0
        public void MenuConfiguration_ConstructorParameterContainerNotNullReturnsMenuConfiguration()
        {
            IUnityContainer fakeUnityContainer = new UnityContainer();

            var menuConfiguration = new MenuConfiguration(fakeUnityContainer);

            menuConfiguration.Configure();

            var isRegistered = fakeUnityContainer.IsRegistered <IMenu>();

            Assert.True(isRegistered);
        }
Ejemplo n.º 22
0
        public void DataLoaderConfiguration_ConfigureAddDataLoaderToConfiguration()
        {
            var fakeUnityContainer = new UnityContainer();

            var dataLoaderConfiguration = new DataLoaderConfiguration(fakeUnityContainer);

            dataLoaderConfiguration.Configure();

            var isRegistered = fakeUnityContainer.IsRegistered <IDataLoader>();

            Assert.True(isRegistered);
        }
Ejemplo n.º 23
0
        public void Can_scan_folder_and_exclude_assemblies_by_using_a_predicate()
        {
            var container = new UnityContainer();

            container.Configure(x => x.Scan(scan =>
            {
                scan.AssembliesInDirectory(Environment.CurrentDirectory, a => a.GetName().Name != "UnityConfiguration.Tests");
                scan.With <FirstInterfaceConvention>();
            }));

            Assert.That(container.IsRegistered <IFooService>(), Is.False);
        }
        public void Does_not_register_when_interface_is_not_found()
        {
            var container = new UnityContainer();

            container.Configure(x => x.Scan(scan =>
            {
                scan.AssemblyContaining <NamedService>();

                scan.With <NamingConvention>().WithInterfaceName(t => "IDoNotExist");
            }));

            Assert.That(container.IsRegistered <INamedService>(), Is.False);
        }
Ejemplo n.º 25
0
        private void RegisterCustomObjectItemType(Type type, string lifeCycle)
        {
            Type interfaceType = null;

            interfaceType = this.GetInterfaceType(type, lifeCycle);

            if (interfaceType == null)
            {
                return;
            }

            if (unityContainer.IsRegistered(interfaceType))
            {
                return;
            }

            switch (GetObjectLifeCycle(lifeCycle))
            {
            case ObjectLifeCycle.Singleton:
                unityContainer.RegisterInstance(interfaceType, Activator.CreateInstance(type));
                break;

            case ObjectLifeCycle.New:
                //判定是否给予该程序集注册了类型,如果没有给予该程序集注册类型,则不进行任何的处理.
                bool flag = ValidationIsRegisterInterceptor(type);
                if (!flag)
                {
                    unityContainer.RegisterType(interfaceType, type);
                }
                else
                {
                    this.RegisterAop(interfaceType, type);
                }

                break;
            }
        }
        public static IUnityContainer GetContainer()
        {
            var container = new UnityContainer();

            container.RegisterType <IMediator, Mediator>();

            var classes = AllClasses.FromAssemblies(typeof(UnityConfiguration).Assembly)
                          .Where(x => x.Name.Contains("Controller") == false && x.FullName.Contains("Data.Model") == false)
                          .ToList();

            container.RegisterTypes(classes, WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);
            container.RegisterInstance <SingleInstanceFactory>(t => container.IsRegistered(t) ? container.Resolve(t) : null);
            container.RegisterInstance <MultiInstanceFactory>(t => container.ResolveAll(t));
            return(container);
        }
Ejemplo n.º 27
0
        private static IMediator 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.IsRegistered(t) ? container.Resolve(t) : null);
            container.RegisterInstance <MultiInstanceFactory>(t => container.ResolveAll(t));

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

            return(mediator);
        }
Ejemplo n.º 28
0
 private static IResponseCachedProvider GetProvider(string name)
 {
     if (!string.IsNullOrEmpty(name))
     {
         try
         {
             if (Container.IsRegistered <IResponseCachedProvider>(name))
             {
                 return(Container.Resolve <IResponseCachedProvider>(name));
             }
         }
         catch (Exception ex)
         {
             // todo: 日志
         }
     }
     return(null);
 }
        public void TryNavigate(string viewName, object parameter)
        {
            if (String.IsNullOrEmpty(viewName))
            {
                return;
            }

            if (!UnityContainer.IsRegistered <object>(viewName))
            {
                return;
            }

            CurrentRegion = RegionManager.Regions[GlobalRegionNames.MainRegion];

            CurrentRegion.NavigationService.RequestNavigate(viewName, new NavigationParameters {
                { "", parameter }
            });
        }
        public void HttpClientCanBeCreatedByUnity()
        {
            UnityContainer unityContainer = new UnityContainer();

            ServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddHttpClient("Google", (c) =>
            {
                c.BaseAddress = new Uri("https://google.com/");
            });
            serviceCollection.BuildServiceProvider(unityContainer);

            Assert.True(unityContainer.IsRegistered <IHttpClientFactory>());
            IHttpClientFactory clientFactory = unityContainer.Resolve <IHttpClientFactory>();
            HttpClient         httpClient    = clientFactory.CreateClient("Google");

            Assert.NotNull(httpClient);
            Assert.Equal("https://google.com/", httpClient.BaseAddress.ToString());
        }