public LifetimeManager CreateLifeTimeManager(LifeTimeManagerType type)
        {
            LifetimeManager result = null;
            switch (type)
            {
                case LifeTimeManagerType.ContainerControlled:
                    result = new ContainerControlledLifetimeManager();
                    break;
                case LifeTimeManagerType.HierarchicalLifetime:
                    result = new HierarchicalLifetimeManager();
                    break;
                case LifeTimeManagerType.PerResolveLifetime:
                    result = new PerResolveLifetimeManager();
                    break;
                case LifeTimeManagerType.ExternallyControlledLifetime:
                    result = new ExternallyControlledLifetimeManager();
                    break;
                case LifeTimeManagerType.PerThreadLifetime:
                    result = new PerThreadLifetimeManager();
                    break;
                case LifeTimeManagerType.TransientLifetime:
                    result = new TransientLifetimeManager();
                    break;
            }

            return result;
        }
 public static void Configurar(IUnityContainer container)
 {
     var tempoVidaHierarquico = new HierarchicalLifetimeManager();
     container.RegisterType<IUnidadeTrabalho, UnidadeTrabalho>(tempoVidaHierarquico);
     container.RegisterType<IRepositorio<Usuario>, RepositorioEf<Usuario>>();
     container.RegisterType<ServicoUsuario>();
 }
Пример #3
0
        private void RegisterBehaviors()
        {
            if (!Container.IsRegistered <unity.IInterceptionBehavior>("TraceBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, TraceBehavior>("TraceBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("TraceIdentityBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, TraceIdentityBehavior>("TraceIdentityBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ClaimsToWindowsTokenBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ClaimsToWindowsTokenBehavior>("ClaimsToWindowsTokenBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ElevatedBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ElevatedBehavior>("ElevatedBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ImpersonationBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ImpersonationBehavior>("ImpersonationBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ProfilingBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ProfilingBehavior>("ProfilingBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("CachingBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, CachingBehavior>("CachingBehavior", lifetime);
            }

            Container.AddNewExtension <BehaviorContainerExtension>()
            .Configure <BehaviorContainerExtension>()
            .SetDefaultInterceptor <unity.InterfaceInterceptor>()
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("ProfilingBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("ElevatedBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("TraceIdentityBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("TraceBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("CachingBehavior"))
            .AddMatchingRule(Container.Resolve <IInterceptRule>("NotUnityInterceptionAssembly"))
            .AddMatchingRule(Container.Resolve <IInterceptRule>("AssemblyNameStartsWith_wslyvh"));
        }
Пример #4
0
        public static IUnityContainer RegistType()
        {
            // TODO: Some will user this manger.
            var lifetimeMngr = new HierarchicalLifetimeManager();

            // TODO: Register type here.
            var container = new UnityContainer()
                .RegisterType<IUsersRepository, UsersRepository>()
                .RegisterType<IWechatAppsRepository, WechatAppsRepository>();

            return container;
        }
Пример #5
0
        public IInjectionContainer GetContainer()
        {
            var hierachicalLifetimeMgr = new HierarchicalLifetimeManager();

            var container = new UnityInjectionContainer();

            container.Register <IClass1, Class1>();
            container.Register <IClass2, Class2>(new TransientLifetimeManager());
            container.Register <IClass3, Class3>(hierachicalLifetimeMgr);

            container.Register <IClass1, Thing>(new InjectionConstructor(DayOfWeek.Wednesday), "thing");

            return(container);
        }
        /// <summary>
        /// Called during the chain of responsibility for a build operation. The
        /// PreBuildUp method is called when the chain is being executed in the
        /// forward direction.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public override void PreBuildUp(IBuilderContext context) 
        {
            IPolicyList lifetimePolicySource;

            var activeLifetime = context.PersistentPolicies.Get<ILifetimePolicy>(context.BuildKey, out lifetimePolicySource);
            if (activeLifetime is HierarchicalLifetimeManager && !ReferenceEquals(lifetimePolicySource, context.PersistentPolicies))         
            {
                // came from parent, add a new Hierarchical lifetime manager locally   
                var newLifetime = new HierarchicalLifetimeManager { InUse = true };
                context.PersistentPolicies.Set<ILifetimePolicy>(newLifetime, context.BuildKey);
                // Add to the lifetime container - we know this one is disposable
                context.Lifetime.Add(newLifetime);
            } 
        }
Пример #7
0
        private void RegisterRepositories()
        {
            if (!Container.IsRegistered <IEventfulRepository>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IEventfulRepository, EventfulRepository>(lifetime,
                                                                                     new InjectionConstructor(new ResolvedParameter <ISyncRestClient>("Eventful")));
            }

            if (!Container.IsRegistered <IApiObjectFactory>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IApiObjectFactory, ApiObjectFactory>(lifetime);
            }
        }
Пример #8
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)
 {
     using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
     {
         container.RegisterType <IUnitOfWork, EfUnitOfWork>(hierarchicalLifetimeManager);
     }
     using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
     {
         container.RegisterType <IProductService, ProductBusiness>(hierarchicalLifetimeManager);
     }
     using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
     {
         container.RegisterType <IProductCategoriesService, ProductCategoryBusiness>(hierarchicalLifetimeManager);
     }
 }
Пример #9
0
        private void RegisterMatchingRules()
        {
            if (!Container.IsRegistered <IInterceptRule>("NotUnityInterceptionAssembly"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IInterceptRule, NotUnityInterceptionAssembly>("NotUnityInterceptionAssembly", lifetime);
            }

            if (!Container.IsRegistered <IInterceptRule>("AssemblyNameStartsWith_wslyvh"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IInterceptRule, AssemblyNameStartsWith>("AssemblyNameStartsWith_wslyvh", lifetime,
                                                                                    new InjectionConstructor("wslyvh."));
            }
        }
 ///<summary>
 ///</summary>
 ///<param name="context"></param>
 public override void PreBuildUp(IBuilderContext context)
 {
     var activeLifetime = context.PersistentPolicies.Get<ILifetimePolicy>(context.BuildKey);
     if (activeLifetime is HierarchicalLifetimeManager)
     {
         // did this come from the local container or the parent?
         var localLifetime = context.PersistentPolicies.Get<ILifetimePolicy>(context.BuildKey, true);
         if (localLifetime == null)
         {
             localLifetime = new HierarchicalLifetimeManager();
             context.PersistentPolicies.Set(localLifetime, context.BuildKey);
             context.Lifetime.Add(localLifetime);
         }
     }
 }
        ///<summary>
        ///</summary>
        ///<param name="context"></param>
        public override void PreBuildUp(IBuilderContext context)
        {
            var activeLifetime = context.PersistentPolicies.Get <ILifetimePolicy>(context.BuildKey);

            if (activeLifetime is HierarchicalLifetimeManager)
            {
                // did this come from the local container or the parent?
                var localLifetime = context.PersistentPolicies.Get <ILifetimePolicy>(context.BuildKey, true);
                if (localLifetime == null)
                {
                    localLifetime = new HierarchicalLifetimeManager();
                    context.PersistentPolicies.Set(localLifetime, context.BuildKey);
                    context.Lifetime.Add(localLifetime);
                }
            }
        }
        public override void PreBuildUp(IBuilderContext context)
        {
            IPolicyList lifetimePolicySource;

            var activeLifetime = context.PersistentPolicies.Get <ILifetimePolicy>(context.BuildKey, out lifetimePolicySource);

            if (activeLifetime is HierarchicalLifetimeManager && !ReferenceEquals(lifetimePolicySource, context.PersistentPolicies))
            {
                // came from parent, add a new Hierarchical lifetime manager locally
                var newLifetime = new HierarchicalLifetimeManager {
                    InUse = true
                };
                context.PersistentPolicies.Set <ILifetimePolicy>(newLifetime, context.BuildKey);
                // Add to the lifetime container - we know this one is disposable
                context.Lifetime.Add(newLifetime);
            }
        }
Пример #13
0
        private void RegisterRestClients()
        {
            if (!Container.IsRegistered <IHttpFactory>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IHttpFactory, HttpFactory>(lifetime);
            }

            if (!Container.IsRegistered <ISyncRestClient>("Eventful"))
            {
                Container.RegisterType <ISyncRestClient, RestClient>(
                    "Eventful",
                    new InjectionConstructor(
                        new ResolvedParameter <IHttpFactory>(),
                        new ResolvedParameter <IRestClientConfiguration>("Eventful")));
            }
        }
Пример #14
0
        public void Issue_37()
        {
            using (IUnityContainer parent = new UnityContainer())
            {
                var manager = new HierarchicalLifetimeManager();
                parent.RegisterType(typeof(MyFoo <>), manager);
                using (var child = parent.CreateChildContainer())
                {
                    var first  = child.Resolve <MyFoo <MockBasic> >(); // first is stored in child.lifetimeContainer
                    var second = child.Resolve <MyFoo <MockBasic> >(); // the same as first (by reference)

                    Assert.IsNotNull(first);
                    Assert.IsNotNull(second);
                    Assert.AreSame(first, second);
                }
            }
        }
        /// <summary>
        /// Called during the chain of responsibility for a build operation. The
        /// PreBuildUp method is called when the chain is being executed in the
        /// forward direction.
        /// </summary>
        /// <param name="context">
        /// Context of the build operation.
        /// </param>
        public override void PreBuildUp(IBuilderContext context)
        {
            // this strategy will execute after LifetimeStrategy, this means that current build key will definitely have lifetime manager, because LifetimeStrategy creates transient lifetime manager for all build keys that have no lifetime policy specified
            // note: we are interested only in persistent lifetimes only, because i.e. perresovle lifetime implementation creates local lifetime managers that will hide real persistent ones
            var originalLifetime = context.PersistentPolicies.Get <ILifetimePolicy>(context.BuildKey);

            if (originalLifetime is TransientLifetimeManager)
            {
                // then applying hierarchical lifetime manager to allow every child container to have its own instance of object being built
                // note: not setting InUse = true here, but not a big deal
                var newLifetime = new HierarchicalLifetimeManager();

                // note: policy will be set in the container itself (but during the current build it may be hidden by local lifetime manager)
                context.PersistentPolicies.Set <ILifetimePolicy>(newLifetime, context.BuildKey);

                // note: it is crucial to add new lifetime manager to container's lifetime to allow proper disposal of created objects
                context.Lifetime.Add(newLifetime);
            }
        }
Пример #16
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            //Unity Configuration
            var container = new UnityContainer();

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IEmployeeRepository, EmployeeRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IEmployeeService, EmployeeService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <ISalaryFactory, SalaryFactory>(hierarchicalLifetimeManager);
            }

            config.DependencyResolver = new UnityResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
                = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

            config.Formatters.JsonFormatter.SerializerSettings.Formatting
                = Newtonsoft.Json.Formatting.Indented;
        }
Пример #17
0
        public static void Register(this IUnityContainer container, IServiceDescriptor serviceDescriptor)
        {
            LifetimeManager lifetimeManager = null;
            switch (serviceDescriptor.Lifecycle)
            {
                case LifecycleKind.Singleton:
                    lifetimeManager = new ContainerControlledLifetimeManager();
                    break;
                case LifecycleKind.Scoped:
                    lifetimeManager = new HierarchicalLifetimeManager();
                    break;
                case LifecycleKind.Transient:
                    lifetimeManager = new TransientLifetimeManager();
                    break;
            }

            if (serviceDescriptor.ImplementationInstance != null)
                container.RegisterInstance(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationInstance);
            else
                container.RegisterType(serviceDescriptor.ServiceType, serviceDescriptor.ImplementationType, lifetimeManager);
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
        /// </summary>
        /// <param name="container">Unity container.</param>
        public UnitOfWork(IUnityContainer container)
        {
            Log.Debug("Going to init UnitOfWork.");

            var watch = new Stopwatch();

            watch.Start();

            var hierarchicalLifetimeManager = new HierarchicalLifetimeManager();
            var injectionConstructor        = new InjectionConstructor();

            container.RegisterType <ObjectContext, dentistEntities>(hierarchicalLifetimeManager, injectionConstructor);
            this.entities = container.Resolve <ObjectContext>();

            this.AppointmentRepository            = container.Resolve <IAppointmentRepository <AppointmentModel, Guid> >();
            this.BackupRepository                 = container.Resolve <IBackupRepository <BackupLogsModel, int> >();
            this.EducationRepository              = container.Resolve <IEducationRepository <EducationModel, int> >();
            this.LoginRepository                  = container.Resolve <ILoginRepository <LoginModel, int> >();
            this.NotificationGroupRepository      = container.Resolve <INotificationGroupRepository <NotificationGroupModel, int> >();
            this.NotificationListRepository       = container.Resolve <INotificationListRepository <NotificationListModel, int> >();
            this.NotificationListStatusRepository = container.Resolve <INotificationListStatusRepository <NotificationListStatusModel> >();
            this.NotificationTemplateRepository   = container.Resolve <INotificationTemplateRepository <NotificationTemplateModel, ItemModel, int> >();
            this.PatientRepository                = container.Resolve <IPatientRepository <PatientModel, ItemModel, int> >();
            this.PositionRepository               = container.Resolve <IPositionRepository <PositionModel, int> >();
            this.RoleRepository           = container.Resolve <IRoleRepository <RoleModel, int> >();
            this.SettingRepository        = container.Resolve <ISettingRepository <SettingModel, AvailableSettings> >();
            this.GenderRepository         = container.Resolve <IGenderRepository <GenderModel> >();
            this.StaffRepository          = container.Resolve <IStaffRepository <StaffModel, ItemModel, int> >();
            this.SystemUpdatesRepository  = container.Resolve <ISystemUpdatesRepository <SystemUpdatesModel> >();
            this.ReminderRepository       = container.Resolve <IReminderRepository <ReminderModel, int> >();
            this.ReminderFilterRepository = container.Resolve <IReminderFilterRepository <ReminderFilterModel> >();
            this.UiCultureRepository      = container.Resolve <IUiCultureRepository <CultureModel> >();
            this.ReminderAlertRepository  = container.Resolve <IReminderAlertRepository <ReminderAlertModel> >();

            watch.Stop();

            Log.Debug("UnitOfWork was initialized. Took {0}", Log.Args(watch.Elapsed));
        }
Пример #19
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 }
            );

            // 使用簡易的 MyDependencyResolver 來取代預設的 EmptyResolver
            //config.DependencyResolver = new MyDependencyResolver();

            // 使用 UnityDependencyResolver 來解析
            var container = new UnityContainer();
            var childLifetimeManager = new HierarchicalLifetimeManager();
            container.RegisterType<ICustomerService, CustomerService>(childLifetimeManager);
            var resolver = new UnityDependencyResolver(container);
            config.DependencyResolver = resolver;
        }
        public override void Execute()
        {
            // Matching Rules
            if (!Container.IsRegistered <IInterceptRule>("NotUnityInterceptionAssembly"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IInterceptRule, NotUnityInterceptionAssembly>("NotUnityInterceptionAssembly", lifetime);
            }

            if (!Container.IsRegistered <IInterceptRule>("AssemblyNameStartsWith_wslyvh"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IInterceptRule, AssemblyNameStartsWith>("AssemblyNameStartsWith_wslyvh", lifetime,
                                                                                    new InjectionConstructor("wslyvh."));
            }

            // Extensions
            Container.AddNewExtension <InterceptionContainerExtension>()
            .Configure <InterceptionContainerExtension>()
            .SetDefaultInterceptor <unity.InterfaceInterceptor>()
            .AddMatchingRule(Container.Resolve <IInterceptRule>("NotUnityInterceptionAssembly"))
            .AddMatchingRule(Container.Resolve <IInterceptRule>("AssemblyNameStartsWith_wslyvh"));

            // Loggers / Providers
            if (!Container.IsRegistered <ILoggerFactory>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <ILoggerFactory, TraceLoggerFactory>(lifetime);
            }

            if (!Container.IsRegistered <ILogger>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <ILogger, TraceLogger>(lifetime, new InjectionConstructor("Default Trace Logger", TraceEventType.Information));
            }

            if (!Container.IsRegistered <IProfiler>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <IProfiler, Profiler>(lifetime);
            }

            if (!Container.IsRegistered <ICachingProvider>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <ICachingProvider, HttpRuntimeCachingProvider>(lifetime);
            }

            // Behaviors
            if (!Container.IsRegistered <unity.IInterceptionBehavior>("TraceBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, TraceBehavior>("TraceBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("TraceIdentityBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, TraceIdentityBehavior>("TraceIdentityBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ClaimsToWindowsTokenBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ClaimsToWindowsTokenBehavior>("ClaimsToWindowsTokenBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ElevatedBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ElevatedBehavior>("ElevatedBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ImpersonationBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ImpersonationBehavior>("ImpersonationBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("ProfilingBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, ProfilingBehavior>("ProfilingBehavior", lifetime);
            }

            if (!Container.IsRegistered <unity.IInterceptionBehavior>("CachingBehavior"))
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <unity.IInterceptionBehavior, CachingBehavior>("CachingBehavior", lifetime);
            }

            Container.AddNewExtension <BehaviorContainerExtension>()
            .Configure <BehaviorContainerExtension>()
            .SetDefaultInterceptor <unity.InterfaceInterceptor>()
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("ProfilingBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("ElevatedBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("TraceIdentityBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("TraceBehavior"))
            .AddBehavior(Container.Resolve <unity.IInterceptionBehavior>("CachingBehavior"))
            .AddMatchingRule(Container.Resolve <IInterceptRule>("NotUnityInterceptionAssembly"))
            .AddMatchingRule(Container.Resolve <IInterceptRule>("AssemblyNameStartsWith_wslyvh"));

            // Mvp
            if (!Container.IsRegistered <ISampleRepository>())
            {
                Container.RegisterType <ISampleRepository, SampleRepository>();
            }

            if (!Container.IsRegistered <ISampleModel>())
            {
                Container.RegisterType <ISampleModel, SampleModel>(new PerRequestLifetimeManager());
            }

            if (!Container.IsRegistered <ISamplePresenter>())
            {
                Container.RegisterType <ISamplePresenter, SamplePresenter>(new PerRequestLifetimeManager());
            }

            CoreContext.Current.Items[ContextKeys.Container] = Container;
        }
Пример #21
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            //Unity Configuration
            var container = new UnityContainer();

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IClientRepository, ClientRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <ICoverageTypeRepository, CoverageTypeRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyCoverageTypeRepository, PolicyCoverageTypeRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyRepository, PolicyRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IRiskTypeRepository, RiskTypeRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IClientService, ClientService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <ICoverageTypeService, CoverageTypeService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyService, PolicyService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IRiskTypeService, RiskTypeService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IUnitOfWork, UnitOfWork>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyCoverageTypeService, PolicyCoverageTypeService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyClientService, PolicyClientService>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IPolicyClientRepository, PolicyClientRepository>(hierarchicalLifetimeManager);
            }

            using (var hierarchicalLifetimeManager = new HierarchicalLifetimeManager())
            {
                container.RegisterType <IRiskFatory, RiskFactory>(hierarchicalLifetimeManager);
            }

            config.DependencyResolver = new UnityResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
                = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

            config.Formatters.JsonFormatter.SerializerSettings.Formatting
                = Newtonsoft.Json.Formatting.Indented;

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
                = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        }
Пример #22
0
        //   DependencyFactory.RegisterDependency(ProjectType.Wcf, "MT.Complex");
        public static void RegisterDependency(ProjectType projecttype, string projectname)
        {
            string DllPath = string.Empty;

            switch ( projecttype )
            {
                case ProjectType.Web:
                    DllPath = AppDomain.CurrentDomain.BaseDirectory + "\\bin\\" + projectname + ".dll";
                    break;
                case ProjectType.Winfom:
                case ProjectType.WPF:
                case ProjectType.Wcf:
                case ProjectType.Test:
                    DllPath = AppDomain.CurrentDomain.BaseDirectory + "\\" + projectname + ".dll";
                    break;

            }
            if ( DllPath == null || DllPath.Length == 0 )
            {
                throw new Exception("无法解析项目DLL");
            }
            var typeList =
                  Assembly.LoadFrom(DllPath).GetTypes().Where(t => t.Namespace != null && t.Namespace.Contains("Realization") && t.IsInterface == false && t.IsAbstract == false);

            var LifetimeManagerRegisterlist =
             typeList.Where(t =>
             {
                 return t.GetInterfaces().Intersect(ILifetimeManagerRegisterList).Count() > 0;
             });

            foreach ( var t in LifetimeManagerRegisterlist )
            {
                var InterfaceList = t.GetInterfaces().Where(p =>
                { 
                    return !ILifetimeManagerRegisterList.Contains(p) && p.GetCustomAttribute(typeof(ICO_AOPEnableAttribute), false) != null;
                });
                LifetimeManager lifetimemanager = new TransientLifetimeManager();
                var intertype = t.GetInterfaces().Intersect(ILifetimeManagerRegisterList).First();
                switch ( intertype.Name )
                {
                    case "IContainerControlledLifetimeManagerRegister":
                        lifetimemanager = new ContainerControlledLifetimeManager();
                        break;
                    case "IHierarchicalLifetimeManagerRegister":
                        lifetimemanager = new HierarchicalLifetimeManager();
                        break;
                    case "IExternallyControlledLifetimeManagerRegister":
                        lifetimemanager = new ExternallyControlledLifetimeManager();
                        break;
                    case "IPerThreadLifetimeManagerRegister":
                        lifetimemanager = new PerThreadLifetimeManager();
                        break;
                    case "IPerResolveLifetimeManagerRegister":
                        lifetimemanager = new PerResolveLifetimeManager();
                        break;
                }

                foreach ( var iType in InterfaceList )
                {
                    ICOConfigAttribute ds = (ICOConfigAttribute) t.GetCustomAttribute(typeof(ICOConfigAttribute), false);
                    ICO_AOPEnableAttribute ia = (ICO_AOPEnableAttribute) iType.GetCustomAttribute(typeof(ICO_AOPEnableAttribute), false);
                     

                    if ( ia.AOPEnable )
                    {
                        var generator = new DynamicProxyGenerator(t, iType);
                        Type type = generator.GenerateType();

                      //  Type type = typeof(TransientLifetimeManager);
                        DependencyUnityContainer.Current.RegisterType(iType, type, ds.Description, lifetimemanager);
                    }
                    else
                    {
                        DependencyUnityContainer.Current.RegisterType(iType, t, ds.Description, lifetimemanager);
                    } 

                }
            }



        }
Пример #23
0
        private void RegisterTypes()
        {
            if (!Container.IsRegistered <ILoggerFactory>())
            {
                using (var lifetime = new HierarchicalLifetimeManager())
                    Container.RegisterType <ILoggerFactory, TraceLoggerFactory>(lifetime);
            }

            if (!Container.IsRegistered <ISettingProvider>())
            {
                Container.RegisterType <ISettingProvider, AppSettingProvider>();
            }

            if (!Container.IsRegistered <ILogger>("MemoryStackLogger"))
            {
                Container.RegisterType <ILogger, MemoryStackLogger>("MemoryStackLogger",
                                                                    new InjectionConstructor("MemoryStackLogger", TraceEventType.Information));
            }

            if (!Container.IsRegistered <ISerializer>("XmlDataSerializer"))
            {
                Container.RegisterType <ISerializer, XmlDataSerializer>("XmlDataSerializer");
            }

            if (!Container.IsRegistered <ISerializer>("DataSerializer"))
            {
                Container.RegisterType <ISerializer, DataSerializer>("DataSerializer");
            }

            if (!Container.IsRegistered <ISerializer>("JsonSerializer"))
            {
                Container.RegisterType <ISerializer, JsonSerializer>("JsonSerializer");
            }

            if (!Container.IsRegistered <ICachingProvider>("HttpRuntimeCachingProvider"))
            {
                Container.RegisterType <ICachingProvider, HttpRuntimeCachingProvider>("HttpRuntimeCachingProvider");
            }

            if (!Container.IsRegistered <ICacheManager>())
            {
                Container.RegisterInstance <ICacheManager>(CreateEntLibCacheManager());
            }

            if (!Container.IsRegistered <ICachingProvider>("EntLibCachingProvider"))
            {
                Container.RegisterType <ICachingProvider, EntLibCachingProvider>("EntLibCachingProvider");
            }

            //if (!Container.IsRegistered<IServiceClient>("RestServiceClient"))
            //    Container.RegisterType<IServiceClient, ServiceClientMock>("RestServiceClient");

            if (!Container.IsRegistered <IServiceClient>("RestServiceClient"))
            {
                Container.RegisterMock <IServiceClient>("RestServiceClient");
            }

            if (!Container.IsRegistered <IServiceClient>("CachedServiceClient"))
            {
                Container.RegisterType <IServiceClient, CachedServiceClient>("CachedServiceClient",
                                                                             new InjectionConstructor(
                                                                                 Container.Resolve <IServiceClient>("RestServiceClient"),
                                                                                 Container.Resolve <ICachingProvider>("HttpRuntimeCachingProvider")));
            }
        }