コード例 #1
1
 private static IUnityContainer BuildUnityContainer()
 {
     var container = new UnityContainer();
     container.RegisterType<IFlightFilterRulesService, FlightFilterRulesService>();
     container.RegisterType<IFlightBuilder, FlightBuilder>();
     return container;
 }
コード例 #2
1
ファイル: WebApiConfig.cs プロジェクト: RubenGomes10/Farma
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            //Unity
            var container = new UnityContainer();
            container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType<IGenericRepository<Farmacia>, GenericRepository<Farmacia>>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            //Formatters
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            //GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //config.Formatters.Insert(0, new System.Net.Http.Formatting.JsonMediaTypeFormatter());

            // Web API routes
            config.MapHttpAttributeRoutes();
            //config.EnableCors();
            var cors = new EnableCorsAttribute("http://localhost:28285", "*", "*");
            config.EnableCors(cors);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
コード例 #3
0
ファイル: WebApiConfig.cs プロジェクト: johnhinz/Investor
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

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

            // IoC Injection setup
            var container = new UnityContainer();
            container.RegisterType<IClientRepository, ClientRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IClientLogic, ClientLogic>(new HierarchicalLifetimeManager());
            container.RegisterType<ILog>(new InjectionFactory(x => LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType)));
            container.RegisterType<IAuthenticationRepository, AuthenticationRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            // JSON serialize settings
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            // CORS setup
            config.EnableCors();

            // Authentication filters
            config.Filters.Add(new BasicAuthenticationFilter());

            //config.SuppressDefaultHostAuthentication();
            //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        }
コード例 #4
0
ファイル: Login.aspx.cs プロジェクト: wjkong/ApiExpert
        public static string LoginUser(string username, string password, string response)
        {
            string result = string.Empty;

            try
            {
                if (!IsRobot(response))
                {
                    IUnityContainer container = new UnityContainer();
                    container.RegisterType<AccountMgr>();
                    container.RegisterType<IAccountDacMgr, AccountDacMgr>();

                    AccountMgr accountMgr = container.Resolve<AccountMgr>();

                    accountMgr.UserName = username;
                    accountMgr.Password = password;

                    if (accountMgr.Login())
                    {
                        FormsAuthentication.SetAuthCookie(accountMgr.UserName, false);

                        result = "OK";
                    }
                }
            }
            catch
            {
                throw;
            }

            return result;
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: ravigonella/going-async
        static void Main(string[] args)
        {
            var arguments = Args.Configuration.Configure<Arguments>().CreateAndBind(args);

            var container = new UnityContainer();
            container.RegisterType<ITradeContextFactory, TradeContextFactory>();

            switch (arguments.Version)
            {
                case "1.0":
                    container.RegisterType<IIncomingTradeProcessor, SynchronousTradeProcessor>();
                    break;
                case "1.1":
                    container.RegisterType<IIncomingTradeProcessor, TaskTradeProcessor>();
                    break;
                case "1.2":
                    container.RegisterType<IIncomingTradeProcessor, ActionBlockTradeProcessor>();
                    break;
            }

            var path = Config.Get("FileWatcher.Path");
            container.RegisterType<IncomingTradeFileWatcher>(new InjectionConstructor(
                                                                new ResolvedParameter<IIncomingTradeProcessor>(),
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                path));

            var watcher = container.Resolve<IncomingTradeFileWatcher>();
            watcher.Start(true);
            Console.WriteLine(" ** v" + arguments.Version + " IncomingTradeFileWatcher listening (Enter to exit) **");
            Console.ReadLine();
            watcher.Dispose();
        }
コード例 #6
0
        private static void RegisterConventions(Microsoft.Practices.Unity.UnityContainer container,
                                                IEnumerable <Assembly> assemblies = null)
        {
            foreach (var type in GetClassesFromAssemblies(assemblies))
            {
                IEnumerable <Type> interfacesToBeRegsitered = GetInterfacesToBeRegistered(type);
                AddToInternalTypeMapping(type, interfacesToBeRegsitered);
            }


            foreach (KeyValuePair <Type, HashSet <Type> > typeMapping in InternalTypeMapping)
            {
                if (typeMapping.Value.Count == 1)
                {
                    var type = typeMapping.Value.First();
                    container.RegisterType(typeMapping.Key, type);
                }
                else
                {
                    foreach (var type in typeMapping.Value)
                    {
                        container.RegisterType(typeMapping.Key, type, GetNameForRegistration(type));
                    }
                }
            }
        }
コード例 #7
0
ファイル: WebApiConfig.cs プロジェクト: laumsporre/matsmat
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            //config.Formatters.Add(new RecipesFormatter());

            config.Filters.Add(new ValidateModelAttribute());

            // Initialize IOC using Unity
            var container = new UnityContainer();
            container.RegisterType<IMatsMatRepository, MatsMatRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IAuthRepository, AuthRepository>(new 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 }
            );

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            //jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Todo: possible enable CamelCase properties
        }
コード例 #8
0
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            var documentUri = ConfigurationManager.AppSettings["DocumentUri"];
            string authKey = ConfigurationManager.AppSettings["AuthorizationKey"];
            string redisConnection = ConfigurationManager.AppSettings["RedisConnection"];

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

            // e.g. container.RegisterType<ITestService, TestService>();
            Uri uri = new Uri(documentUri);
            ConnectionPolicy connectionPolicy = new ConnectionPolicy() { ConnectionMode = ConnectionMode.Direct, ConnectionProtocol = Protocol.Tcp };
            ConsistencyLevel consistencyLevel = new ConsistencyLevel();
            consistencyLevel = ConsistencyLevel.Session;

            container.RegisterType<IApplicationUserStore, ApplicatonUserStore>();
            container.RegisterType<DocumentClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor(uri, authKey, connectionPolicy, consistencyLevel));

            ConnectionMultiplexer connectionMulp = ConnectionMultiplexer.Connect(redisConnection);
            container.RegisterInstance<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(redisConnection));

            container.RegisterType<IRedisRepository, RedisRepository>();
            container.RegisterType<IUserRepository, UserRepository>();

            var repo = container.Resolve<IRedisRepository>();

            container.RegisterType<RefreshTokenProvider>(new InjectionConstructor(repo));

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: nthandu/FlightSummary
 private static void RegisterTypes(UnityContainer container)
 {
     container.RegisterType<ISummary, Core.Models.Summary>();
     container.RegisterType<ISummaryFormatter, Core.Fomatters.SimpleSummaryFormatter>();
     container.RegisterType<IReader, Core.Readers.SimpleFileReader>();
     container.RegisterType<IInputValidator, SimpleInputValidator>();
 }
コード例 #10
0
ファイル: ControllerModel.cs プロジェクト: GeorgeMi/PollApp
 public ControllerModel()
 {
     IUnityContainer objContainer = new UnityContainer();
     objContainer.RegisterType<BusinessLogic.BusinessLogic>();
     objContainer.RegisterType<DataAccess.IDataAccess, DataAccess.DataAccess>();
     bl = objContainer.Resolve<BusinessLogic.BusinessLogic>();
 }
コード例 #11
0
ファイル: Program.cs プロジェクト: pvx/ShopOrder
        static void Main()
        {
            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType<Logger>();
                container.RegisterType<IOrderUserInfo, OrderUserInfo>(new ContainerControlledLifetimeManager(),
                                        new InjectionConstructor(Settings.Default.Server,
                                        Settings.Default.Database,
                                        Settings.Default.User,
                                        Settings.Default.Password));

                container.RegisterType<IOrderConnection, OrderConnection>();
                container.RegisterType<OrderDataContext>();

                container.RegisterType<OrderRepo>();

                container.RegisterType<DataClass>();
                container.RegisterType<OrderView>();
                container.RegisterType<SupervisorModel>();

                container.RegisterType<LoginView>();
                container.RegisterType<MainView>();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(container.Resolve<MainView>());
            }
        }
コード例 #12
0
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings["WhaConnection"];

            string providerName = connectionStringSettings.ProviderName;
            string connectionString = connectionStringSettings.ConnectionString;

            DbProviderFactory databaseProviderFactory = DbProviderFactories.GetFactory(providerName);

            container.RegisterInstance(databaseProviderFactory);

            // e.g. container.RegisterType<ITestService, TestService>();
            //container.Register(c => new KiggDbFactory(c.Resolve<DbProviderFactory>(), connectionString)).As<IKiggDbFactory>().InstancePerLifetimeScope();
            //container.Register(c => new QueryFactory(c.Resolve<IKiggDbFactory>(), true)).As<IQueryFactory>().SingleInstance();

            container.RegisterInstance<IWhaDbFactory>(new WhaDbFactory(databaseProviderFactory, connectionString));//.As<IWhaDbFactory>().InstancePerLifetimeScope();

            //container.RegisterType<IWhaDbFactory, WhaDbFactory>();
            container.RegisterType<IQueryFactory, QueryFactory>();

            container.RegisterType<ITourRepository, TourRepository>();
            container.RegisterType<ILocationRepository, LocationRepository>();
            return container;
        }
コード例 #13
0
ファイル: WebApiConfig.cs プロジェクト: mkwie/mobRepo
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            var container = new UnityContainer();

            container.RegisterType<IStationRepository, StationRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<ICarRepository, CarRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IWorkerRepository, WorkerRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<ICustomerRepository, CustomerRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IOrderRepository, OrderRepository>(new 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.Routes.MapHttpRoute(
                name: "ApiByName",
                routeTemplate: "api/{controller}/{action}/{name}",
                defaults: new {action = "Get" }
            );
        }
コード例 #14
0
        public static void Run()
        {
            var container = new UnityContainer();

            container.RegisterType<IConfiguration, LocalConfiguration>(new ContainerControlledLifetimeManager());
            IConfiguration configuration = container.Resolve<IConfiguration>();
            container.RegisterType<ILogger, EventLogLogger>();
            container.RegisterType<IQueueAdapter, QueueAdapter>();

            IQueueAdapter adapter = container.Resolve<IQueueAdapter>();

            string msmqNonTransactionalPath1 = configuration["msmqNonTransactionalPath1"];

            adapter.CreateQueue(msmqNonTransactionalPath1);

            while (!Console.KeyAvailable)
            {
                Console.WriteLine(
                    string.Format(
                        "{0}: {1}",
                        msmqNonTransactionalPath1,
                        adapter.SendMessage(msmqNonTransactionalPath1, new MentoringMessage())));
                Thread.Sleep(1000);
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: krishanthaI/GlobalX-Test
        private static void Main(string[] args)
        {
            #if DEBUG
            args = new[] {@"C:\GitHUB-Applications\GlobalX-Test\NameSort\NameSort\InputFile\names.txt"};
            #endif
            string inputFileUrl = args[0];
            string outputFileUrl = string.Format("{0}\\{1}", Path.GetDirectoryName(inputFileUrl), "names-sorted.txt");

            try
            {
                IUnityContainer unitycontainer = new UnityContainer();
                unitycontainer.RegisterType<ISortData, SortData>();
                unitycontainer.RegisterType<ITextFile, TextFile>();

                var nameSort = unitycontainer.Resolve<TextFileNameSort>();
                IEnumerable<Name> data = nameSort.Read(inputFileUrl);
                IEnumerable<Name> sortedData = nameSort.Sort(data);

                IList<Name> sortedDataCollection = sortedData as IList<Name> ?? sortedData.ToList();
                nameSort.Save(sortedDataCollection, outputFileUrl);

                sortedDataCollection.ForEach(n => Console.WriteLine(n.ToString()));

                Console.Write("Finished: created {0}", outputFileUrl);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
コード例 #16
0
        public void Combined_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<DisposableClass>("transient", new DisposingTransientLifetimeManager());
            container.RegisterType<DisposableClass>("shared", new DisposingSharedLifetimeManager());

            var transient1 = container.Resolve<DisposableClass>("transient");
            var transient2 = container.Resolve<DisposableClass>("transient");
            Assert.AreNotEqual(transient1, transient2);

            var shared1 = container.Resolve<DisposableClass>("shared");
            Assert.AreNotEqual(transient1, shared1);
            Assert.AreNotEqual(transient2, shared1);

            var shared2 = container.Resolve<DisposableClass>("shared");
            Assert.AreEqual(shared1, shared2);

            container.Teardown(transient1);
            Assert.IsTrue(transient1.Disposed);

            container.Teardown(shared2);
            Assert.IsFalse(shared2.Disposed);

            container.Teardown(shared1);
            Assert.IsTrue(shared1.Disposed);
        }
コード例 #17
0
        public static void Register(HttpConfiguration config)
        {
            // Dependency resolver for dependency injection
            UnityContainer container = new UnityContainer();
            container.RegisterType<IResearchRepository, ResearchRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IProjectsRepository, ProjectsRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<IReferencesRepository, ReferencesRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            config.MapHttpAttributeRoutes();

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

            //OData Models
            ODataModelBuilder odataBuilder = new ODataConventionModelBuilder();
            odataBuilder.Namespace = "SpResearchTracker.Models";
            odataBuilder.EntitySet<Project>("Projects");
            odataBuilder.EntitySet<Reference>("References");

            // OData routes
            config.Routes.MapODataRoute(
              routeName: "odata",
              routePrefix: "odata",
              model: odataBuilder.GetEdmModel(),
              batchHandler: new BreezeODataBatchHandler(GlobalConfiguration.DefaultServer));
        }
コード例 #18
0
 private static IUnityContainer BuildUnityContainer()
 {
     var container = new UnityContainer();
     container.RegisterType<IPersonaRepository, PersonaRepository>();
     container.RegisterType<IController, PersonaController>("Persona");
     return container;
 }
コード例 #19
0
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            HttpConfiguration config = new HttpConfiguration();

            //filters
            config.Filters.Add(new CustomerValidationModelAttribute());
            // config.Filters.Add(new AuthorizeAttribute());

            //Dependency Resolution
            var container = new UnityContainer();
            container.RegisterType<IOrderRepository, InMemoryOrderRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<ICustomerRepository, InMemoryCustomerRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<ISubscriptionRepository, InMemorySubscriptionRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<ITokenRepository, InMemoryTokenRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);

            //Handlers
            config.MessageHandlers.Add(new MsTrackingHandler());

            // Web API configuration and services
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.EnableSystemDiagnosticsTracing();

            builder.UseWebApi(config);
        }
コード例 #20
0
ファイル: WebApiConfig.cs プロジェクト: uheerme/core
        /// <summary>
        /// initiates the UnityContainer and registers the services.
        /// </summary>
        /// <param name="config"></param>
        public static void Register(HttpConfiguration config)
        {
            var container = new UnityContainer();
            container.RegisterType<DbContext, UheerContext>(new HierarchicalLifetimeManager());
            container.RegisterType<IUserStore<User>, UserStore<User>>(new HierarchicalLifetimeManager());

            config.DependencyResolver = new UnityResolver(container);

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
コード例 #21
0
        public static void Setup(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 }
            );

            // Unity Dependency Injection
            var container = new UnityContainer();
            IDBConnection databaseConnection = new DBConnection();

            container.RegisterInstance<IDBConnection>(databaseConnection);
            container.RegisterType<IScrapeTaskFactory, ScrapeTaskFactory>();
            container.RegisterType<IScrapeTaskRepository, ScrapeTaskRepository>();
            container.RegisterType<IBillingAccountRepository, BillingAccountRepository>();
            container.RegisterType<ISchedule, Schedule>();

            config.DependencyResolver = new UnityResolver(container);
        }
コード例 #22
0
ファイル: UnityConfig.cs プロジェクト: tboyce/HelloWebApi
        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);
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: phatcher/unity.extensions
    static void Main(string[] args)
    {
      IUnityContainer container = new UnityContainer();
      container.AddNewExtension<TypeTrackingExtension>();

      container.RegisterType<IFoo, AFoo>();
      container.RegisterType<IFoo, AnotherFoo>("Named");

      Console.WriteLine("CanResolve<IFoo>() == {0}", container.CanResolve<IFoo>());
      Console.WriteLine("CanResolve<IFoo>(\"Named\") == {0}", container.CanResolve<IFoo>("Named"));
      Console.WriteLine("CanResolve<IBar>() == {0}", container.CanResolve<IBar>());

      Console.WriteLine("TryResolve<IFoo>() == null ==> {0}", container.TryResolve<IFoo>() == null);
      Console.WriteLine("TryResolve<IFoo>(\"Named\") == null ==> {0}", container.TryResolve<IFoo>("Named") == null);
      Console.WriteLine("TryResolve<IBar>() == null ==> {0}", container.TryResolve<IBar>() == null);
      
      Console.WriteLine("TryResolve<IBar>(new ABar()) == null ==> {0}", container.TryResolve<IBar>(new ABar()) == null);
      Console.WriteLine("TryResolve<IBar>(\"Named\", new ABar()) == null ==> {0}", container.TryResolve<IBar>("Named", new ABar()) == null);

      Console.WriteLine("ResolveAllToEnumerable<IFoo>().Count() == {0}", container.ResolveAllToEnumerable<IFoo>().Count());
      Console.WriteLine("ResolveAllToEnumerable<IFoo>(false).Count() == {0}", container.ResolveAllToEnumerable<IFoo>(false).Count());
      Console.WriteLine("ResolveAllToEnumerable<IBar>().Count() == {0}", container.ResolveAllToEnumerable<IBar>().Count());

      Console.WriteLine("ResolveAllToArray<IFoo>().Length == {0}", container.ResolveAllToArray<IFoo>().Length);
      Console.WriteLine("ResolveAllToArray<IFoo>(false).Length == {0}", container.ResolveAllToArray<IFoo>(false).Length);
      Console.WriteLine("ResolveAllToArray<IBar>().Length == {0}", container.ResolveAllToArray<IBar>().Length);

      Console.ReadLine();
    }
コード例 #24
0
        public void UnityCanResolveEnumerableOfTypesRegisteredInUnityTest()
        {
            // Setup
            var unityContainer = new UnityContainer();

            // Add composition support for unity
            unityContainer.AddNewExtension<LazySupportExtension>();

            Component1.InstanceCount = 0;
            Component2.InstanceCount = 0;

            unityContainer.RegisterType<IComponent, Component1>("component1");
            unityContainer.RegisterType<IComponent, Component2>("component2");
            unityContainer.RegisterType<IComponent, Component3>();

            var collectionOfLazyUnityComponents = unityContainer.Resolve<IEnumerable<IComponent>>();
            Assert.That(collectionOfLazyUnityComponents, Is.Not.Null);

            Assert.That(Component1.InstanceCount, Is.EqualTo(1));
            Assert.That(Component2.InstanceCount, Is.EqualTo(1));

            var list = new List<IComponent>(collectionOfLazyUnityComponents);
            Assert.That(list.Count, Is.EqualTo(3));

            Assert.That(list.OfType<Component1>().Count(), Is.EqualTo(1));
            Assert.That(list.OfType<Component2>().Count(), Is.EqualTo(1));
            Assert.That(list.OfType<Component3>().Count(), Is.EqualTo(1));
        }
コード例 #25
0
ファイル: App.xaml.cs プロジェクト: mafafa/WiDroid
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            using (UnityContainer container = new UnityContainer())
            {
                // Load settings
                int discoveryPort = WiDroid.Properties.Settings.Default.DiscoveryPort;

                // Create Unity container and load all types
                container.RegisterType<MainViewModel>();
                container.RegisterType<SettingsViewModel>(new InjectionProperty("DiscoveryPort", discoveryPort), 
                    new InjectionProperty("SettingsCurrentState", SettingsViewModel.SettingsState.Default));
                container.RegisterType<FileTransferViewModel>();

                // Start client discovery server
                ClientDiscoveryServer.ClientDiscoveryServer discoveryServer = new ClientDiscoveryServer.ClientDiscoveryServer(discoveryPort);
                discoveryServer.Start();

                // Show main window
                MainWindow mainWindow = new MainWindow();
                MainViewModel mainViewModel = container.Resolve<MainViewModel>();
                mainWindow.DataContext = mainViewModel;
                mainWindow.ViewModel = mainViewModel;

                FlowManager.Instance.AppWindow = mainWindow;
                FlowManager.Instance.ViewModelContainer = container;

                mainWindow.Show();
            }
        }
コード例 #26
0
ファイル: UnityConfig.cs プロジェクト: rucka/RealWorldCqrs
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.RegisterType<IDocumentStore>(new TransientLifetimeManager()/*new ContainerControlledLifetimeManager()*/, new InjectionFactory(c =>
                {
                    var store = new DocumentStore()
                        {
                            Url = "http://localhost:8080"
                        };

                    //store.Conventions
                    //    .FindIdentityProperty = prop => prop.Name.Equals("key", StringComparison.InvariantCultureIgnoreCase);

                    store.Initialize();
                    return store;
                }))
            ;

            container.RegisterType<IQueryStorage, RavenDbUpdateStorage>();

            const string address = "rabbitmq://localhost/rwcqrs-web";
            var bus = ServiceBusFactory.New(sbc =>
            {
                sbc.UseRabbitMq();
                sbc.ReceiveFrom(address);
            });
            container.RegisterInstance(bus);
            return container;
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: rhaly/RxWorkshop
        private IUnityContainer BuildUpContainer()
        {
            var container =  new UnityContainer();

            container.RegisterType<IUdpClientServer, UdpClientServer>(new ContainerControlledLifetimeManager());

            var serverAddress = ConfigurationManager.AppSettings.Get("ServerAddress");
            var serverPort = int.Parse(ConfigurationManager.AppSettings.Get("ServerPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Server, new ChannelConfig { Address = serverAddress, Port = serverPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Server,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Server))));

            var clientAddress = ConfigurationManager.AppSettings.Get("ClientAddress");
            var clientPort = int.Parse(ConfigurationManager.AppSettings.Get("ClientPort"));
            container.RegisterInstance<IChannelConfig>(ChannelNames.Client, new ChannelConfig { Address = clientAddress, Port = clientPort }, new ContainerControlledLifetimeManager());
            container.RegisterType<ICommunicationChannel, UdpCommunicationChannel>(
                ChannelNames.Client,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(c => new UdpCommunicationChannel(c.Resolve<IUdpClientServer>(), c.Resolve<IChannelConfig>(ChannelNames.Client))));

            container.RegisterType(typeof(IService<,>), typeof(Service<,>), new ContainerControlledLifetimeManager());
            container.RegisterType(typeof(ITopic<>), typeof(Topic<>), new ContainerControlledLifetimeManager());

            var ch = container.Resolve<ICommunicationChannel>(ChannelNames.Client);
            ch.SendMessage(new UserQuery("xxx"));

            container.RegisterType(typeof(IRepoWatch), typeof(RepoWatch), new ContainerControlledLifetimeManager());
            container.RegisterType<RepoHub>(new InjectionFactory(c => new RepoHub(c.Resolve<IRepoWatch>())));

            return container;
        }
コード例 #28
0
ファイル: WebApiConfig.cs プロジェクト: bob1457/WBooking
        public static void Register(HttpConfiguration config)
        {
            
            // Web API configuration and services
            //
            var container = new UnityContainer();

            //Service registration
            container.RegisterType<ITestService, TestService>(new HierarchicalLifetimeManager());

            //Data repository registration
            container.RegisterType<ITestRepo, TestRepo>(new HierarchicalLifetimeManager());



            config.DependencyResolver = new UnityDiResolver(container);


            // Web API routes - attribute routing
            //
            config.MapHttpAttributeRoutes();

            // Web API routes - conventional routing
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: ravigonella/going-async
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container.RegisterType<ITradeContextFactory, TradeContextFactory>();

            container.RegisterType<IMessageHandler, ValidateTradeHandler>("ValidateTradeHandler");
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty1Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                true, false));
            container.RegisterType<IMessageHandler, EnrichPartyHandler>("EnrichParty2Handler",
                                                        new InjectionConstructor(
                                                                new ResolvedParameter<ITradeContextFactory>(),
                                                                false, true));

            container.RegisterType<MessageHandlerFactory>();

            _HandlerFactory = container.Resolve<MessageHandlerFactory>();

            var arguments = Args.Configuration.Configure<Arguments>().CreateAndBind(args);
            var queue = new MessageQueue(arguments.InputQueue, QueueAccessMode.Receive);
            while (true)
            {
                var msg = queue.Receive();
                Handle(msg);
            }
        }
コード例 #30
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            _container = new UnityContainer();
            _container.RegisterInstance<IUnityContainer>(_container);
            var locator = new UnityServiceLocator(_container);
            ServiceLocator.SetLocatorProvider(() => locator);

            _container.RegisterType<UserProvider>(new ContainerControlledLifetimeManager());

            _container.RegisterType<IChildViewModelManager, ChildViewModelManager>(new ContainerControlledLifetimeManager());
            _container.RegisterType<UserDetailsViewModel>(new ContainerControlledLifetimeManager());
            _container.RegisterType<UserListViewModel>(new ContainerControlledLifetimeManager());

            var mappingResolver = new MappingViewTypeResolver();
            mappingResolver.RegisterTypeMapping<UserDetailsView, UserDetailsViewModel>();
            mappingResolver.RegisterTypeMapping<UserListView, UserListViewModel>();
            mappingResolver.RegisterTypeMapping<UserDetailsWindow, UserDetailsWindowViewModel>();
            _container.RegisterInstance<IViewTypeResolver>(mappingResolver);
            var mainVM = _container.Resolve<MainWindowViewModel>();
            mainVM.Initialize();

            var mainWindow = new MainWindow();
            mainWindow.DataContext = mainVM;
            mainWindow.Show();
        }
コード例 #31
0
ファイル: Bootstrapper.cs プロジェクト: tuanva90/mvccodefirst
    private static IUnityContainer BuildUnityContainer()
    {
      var container = new UnityContainer();

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

      // e.g. container.RegisterType<ITestService, TestService>();
      container.RegisterType<UDI.EF.DAL.IEFContext, UDI.EF.DAL.EFContext>(new ContainerControlledLifetimeManager());
      container.Resolve<UDI.EF.DAL.IEFContext>();
      //container.RegisterType(typeof(IRepository<>), typeof(EFGenericRepository<>));
      //Bind the various domain model services and repositories that e.g. our controllers require   

      //Register interfaces in CORE
      container.RegisterType(typeof(UDI.CORE.Repositories.IRepository<>), typeof(UDI.EF.Repositories.EFRepositoryBase<>));
      container.RegisterType<UDI.CORE.Services.ICategoryService, UDI.CORE.Services.Impl.CategoryService>();
      container.RegisterType<UDI.CORE.Services.ICustomerService, UDI.CORE.Services.Impl.CustomerService>();
      container.RegisterType<UDI.CORE.Services.IOrderService, UDI.CORE.Services.Impl.OrderService>();
      container.RegisterType<UDI.CORE.Services.IProductService, UDI.CORE.Services.Impl.ProductService>();
      container.RegisterType<UDI.CORE.Services.IUserService, UDI.CORE.Services.Impl.UserService>();
      container.RegisterType<UDI.CORE.UnitOfWork.IUnitOfWork, UDI.EF.UnitOfWork.EFUnitOfWork>(new ContainerControlledLifetimeManager());
      container.Resolve<UDI.CORE.UnitOfWork.IUnitOfWork>();
      container.RegisterType<UDI.CORE.UnitOfWork.IUnitOfWorkManager, UDI.EF.UnitOfWork.EFUnitOfWorkManager>();
      //Register interfaces in EF
      container.RegisterType<UDI.EF.DAL.IEFContext, UDI.EF.DAL.EFContext>();

      //return container;
      RegisterTypes(container);

      return container;
    }
コード例 #32
0
 private void Application_Startup(object sender, StartupEventArgs e)
 {
     ioc.RegisterInstance(typeof(ILogging.ILoggingFactory), typeof(ILogging.ILoggingFactory).Name, logFactory, new Unity.ContainerControlledLifetimeManager());
     ioc.RegisterType(typeof(IRepo.IRepositoryFactory), typeof(Repo.RepositoryFactory), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IBankRepo), typeof(Repo.BankRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IBelegRepo), typeof(Repo.BelegRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
     ioc.RegisterType(typeof(IRepo.IFAKategorieRepo), typeof(Repo.FAKategorieRepo), typeof(IRepo.IBankRepo).Name, new Unity.TransientLifetimeManager(), new Unity.InjectionMember[0]);
 }
コード例 #33
0
        private static void RegisterTypes(string[] args)
        {
            Container.RegisterType <IApplication, Application>();
            Container.RegisterInstance <IApplicationArguments>(new CommandLineArguments(args));

            Container.RegisterType <IValidatorManager, ValidatorManager>();
            Container.RegisterType <IPrinter, ConsolePrinter>();
            Container.RegisterType <IDateFormatter, DateFormatter>();
            Container.RegisterType <IFormatter, DateRangeFromatter>();
            Container.RegisterType <IArgumentWrapper, ArgumentWrapper>();
            Container.RegisterType <IEnvironment, EnvironmentControl>();
        }
コード例 #34
0
ファイル: TestHelpers.cs プロジェクト: chouteau/QMailer
        public static void Initialize()
        {
            var container = new Microsoft.Practices.Unity.UnityContainer();

            GlobalConfiguration.Configuration.DependencyResolver = new QMailer.UnityDependencyResolver(container);

            GlobalConfiguration.Configuration.FullUrl     = "http://localhost";
            GlobalConfiguration.Configuration.SenderEmail = "*****@*****.**";
            GlobalConfiguration.Configuration.SenderName  = "TestEmail";

            var existingBus = container.Resolve <Ariane.IServiceBus>();

            container.RegisterType <Ariane.IServiceBus, Ariane.SyncBusManager>(new ContainerControlledLifetimeManager(), new InjectionConstructor(existingBus));

            var bus = container.Resolve <Ariane.IServiceBus>();

            bus.Register.AddQueue(new QueueSetting()
            {
                AutoStartReading = true,
                Name             = GlobalConfiguration.Configuration.EmailBodyRequestedQueueName,
                TypeMedium       = typeof(Ariane.InMemoryMedium),
                TypeReader       = typeof(QMailer.Web.EmailBodyRequestedMessageReader)
            });
            bus.Register.AddQueue(new QueueSetting()
            {
                AutoStartReading = true,
                Name             = GlobalConfiguration.Configuration.SendEmailQueueName,
                TypeMedium       = typeof(Ariane.InMemoryMedium),
                TypeReader       = typeof(QMailer.SendEmailMessageReader)
            });

            QMailerService.ReplaceBusService(bus);
            QMailer.Web.QMailerConfig.Configure(container);

            var viewEngines = new Moq.Mock <ViewEngineCollection>();
            var fakeView    = new FakeView();

            viewEngines.Setup(i => i.FindView(Moq.It.IsAny <ControllerContext>(), "test", null))
            .Returns(new ViewEngineResult(fakeView, Moq.Mock.Of <IViewEngine>()));

            var fakeRenderer = new QMailer.Web.EmailViewRenderer(viewEngines.Object, "http://localhost", "~/emailviews");

            container.RegisterInstance <QMailer.Web.IEmailViewRenderer>(fakeRenderer, new ContainerControlledLifetimeManager());

            container.RegisterType <QMailer.ILogger, QMailer.DiagnosticsLogger>(new ContainerControlledLifetimeManager());
        }
コード例 #35
0
 private static void CriarContainer()
 {
     _unityContainer = new Microsoft.Practices.Unity.UnityContainer();
     _unityContainer
     .RegisterType <IGaleryCreator, GaleryCreator>
         (new HttpContextLifetimeManager <IGaleryCreator>())
     .RegisterType <IImagesRepository, ImagesRepository>
         (new HttpContextLifetimeManager <IImagesRepository>());
 }
コード例 #36
0
        public void TestInit()
        {
            // IoCcontainer anlegen
            IoCContainer = new Microsoft.Practices.Unity.UnityContainer();

            // Typen im IOC Container registrieren

            // Achtung: Mock.User hat zwei Konstruktoren. Mittels Attribut InjectionController
            // wird einer für die DI- ausgewählt
            IoCContainer.RegisterType <IUser, Mocks.User>(new InjectionConstructor("unbekannt"));

            IoCContainer.RegisterType <ICanvasScript, Mocks.CanvasScript>();

            // Achtung: die Repositorys sollen als Singletons ausgewählt werden. Dazu ist ein spezieller
            // Lifetime- Manager zu setzen
            // https://msdn.microsoft.com/de-de/library/dn178463(v=pandp.30).aspx#_Lifetime_Management
            IoCContainer.RegisterType <UserRepository, Mocks.UsersRepository>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());
            IoCContainer.RegisterType <CanvasScriptRepository, Mocks.CanvasScriptsRepository>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());

            IoCContainer.RegisterType <ICanvasScriptServerUnitOfWork, Mocks.CanvasScriptServerUnitOfWork>();
        }
コード例 #37
0
        public static IUnityContainer BuildUnityContainer()
        {
            Microsoft.Practices.Unity.UnityContainer container = new Microsoft.Practices.Unity.UnityContainer();

            container.RegisterType <ITestService, TestService>();
            container.RegisterType <IUserService, UserService>();
            container.RegisterType <IRoleService, RoleService>();
            container.RegisterType <ITestResultService, TestResultService>();
            container.RegisterType <IAnswerService, AnswerService>();
            container.RegisterType <IQuestionService, QuestionService>();

            UnityBllConfig.BuildUnityBllContainer(container);

            return(container);
        }
コード例 #38
0
 public void Register(ref Microsoft.Practices.Unity.UnityContainer container)
 {
     container.RegisterType <Context, Context>(new HierarchicalLifetimeManager());
 }
コード例 #39
0
        private static void Main(string[] args)
        {
            DoStuff();
            Console.WriteLine();

            DoAnotherStuff();
            Console.WriteLine();

            DoMoreStuff();
            Console.WriteLine();

            DoBetterStuff();
            Console.WriteLine();

            InterceptedViaInjection();
            Console.WriteLine();

            #region Autofac adapter demo

            // autofac container
            var afContainerBuilder = new ContainerBuilder();

            afContainerBuilder
            .RegisterType <InterceptorForContainer>()
            .As <ITypedInterceptor>();

            var afContainer = afContainerBuilder.Build();

            // cop adapter
            var afCopAdapter = new CodeCop.Setup.Autofac.AutofacContainerAdapter(afContainer);

            #endregion

            #region Castle.Windsor adapter demo

            var cwContainer = new WindsorContainer();

            cwContainer.Register(
                Component
                .For <ITypedInterceptor>()
                .ImplementedBy <InterceptorForContainer>()
                );

            var cwCopAdapter = new CodeCop.Setup.Castle.Windsor.CastleWindsorContainerAdapter(cwContainer);

            #endregion

            #region Ninject adapter demo

            var nContainer = new StandardKernel();

            nContainer
            .Bind <ITypedInterceptor>()
            .To <InterceptorForContainer>();

            var nCopAdapter = new CodeCop.Setup.Ninject.NinjectContainerAdapter(nContainer);

            #endregion

            #region StructureMap adapter demo

            var smContainer = new global::StructureMap.Container();

            smContainer
            .Configure(c =>
            {
                c.For <ITypedInterceptor>()
                .Use <InterceptorForContainer>();
            });

            var smCopAdapter = new CodeCop.Setup.StructureMap.StructureMapContainerAdapter(smContainer);

            #endregion

            #region Unity adapter demo

            var uContainer = new Microsoft.Practices.Unity.UnityContainer();

            uContainer.RegisterType <ITypedInterceptor, InterceptorForContainer>();

            var uCopAdapter = new CodeCop.Setup.Unity.UnityContainerAdapter(uContainer);

            #endregion

            Setup
            .Build(afCopAdapter)     // pass the adapter
            .InterceptMethodIn <Program>(nameof(DoStuff), Intercept.Before,
                                         ctx =>
            {
                Console.WriteLine("InterceptOn.Before > DoStuff !");
                return(null);
            })
            .InterceptMethodIn <Program>(nameof(DoAnotherStuff), new MyInterceptor())
            .UseInterceptor(new ProgramTypedInterceptor())
            .Create()
            .Activate();

            DoStuff();
            Console.WriteLine();

            DoAnotherStuff();
            Console.WriteLine();

            DoMoreStuff();
            Console.WriteLine();

            DoBetterStuff();
            Console.WriteLine();

            InterceptedViaInjection();
            Console.WriteLine();
        }
コード例 #40
0
 public void Register(ref Microsoft.Practices.Unity.UnityContainer container)
 {
     container.RegisterType <A.Core.PermissionModule.Interfaces.IPermissionChecker, PermissionChecker>(new HierarchicalLifetimeManager());
     container.RegisterType <A.Core.PermissionModule.Interfaces.IPermissionService, PermissionService>(new HierarchicalLifetimeManager());
     container.RegisterType <A.Core.PermissionModule.Interfaces.IRoleService, RoleService>(new HierarchicalLifetimeManager());
 }
コード例 #41
0
 public void Register(Microsoft.Practices.Unity.UnityContainer container)
 {
     container.RegisterType <A.Core.Interfaces.IProductService, ProductService>(new HierarchicalLifetimeManager());
     container.RegisterType <A.Core.Interfaces.IAddressService, AddressService>(new HierarchicalLifetimeManager());
     container.RegisterType <A.Core.Interfaces.ICurrencyService, CurrencyService>(new HierarchicalLifetimeManager());
 }