public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Remove XML formatter var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; config.Formatters.Remove(config.Formatters.XmlFormatter); // NetIn and assign a dependency resolver for Web API to use. var dependencyResolver = new DependencyResolver(); config.DependencyResolver = dependencyResolver; // Filter for loggering var logActionFilter = new Containerizer.Filters.LogActionFilter(DependencyResolver.logger); config.Filters.Add(logActionFilter); var exceptionLoggingFilter = new Containerizer.Filters.ExceptionLoggingFilter(DependencyResolver.logger); config.Filters.Add(exceptionLoggingFilter); // Make sure the Autofac lifetime scope is passed to Web API. app.UseAutofacWebApi(config); app.MapWebSocketPattern<ContainerProcessHandler>("/api/containers/(?<handle>.*)/run", dependencyResolver); app.UseWebApi(config); }
public void CanRegisterDependency() { var resolver = new DependencyResolver(); resolver.Register<IFoo>(new Foo()); Assert.IsTrue(true); }
public void InvalidNotPresentValueThrows() { MockBuilderContext context = CreateContext(); DependencyResolver resolver = new DependencyResolver(context); resolver.Resolve(typeof(object), typeof(object), null, (NotPresentBehavior)254, SearchMode.Local); }
public void testRegisterSpecificInstanceSingleton() { DependencyResolver dependencyResolver = new DependencyResolver(); ConsoleLogger theLogger = new ConsoleLogger(); dependencyResolver.Register<ILogger, ConsoleLogger>(theLogger); Assert.IsTrue(theLogger.getID() == dependencyResolver.Resolve<ILogger>().getID()); }
public static IDependencyResolver CreateStandardResolver() { Config config = new Config(); var resolver = new DependencyResolver(config); return resolver; }
public void DoREslove() { DependencyResolver resolver = new DependencyResolver(); //var nietak = new TransferMoney(new IngTransferHandle(), new IngLogTransfer()); var result = resolver.Resolve<TransferMoney>(); result.DoTransfer(new BankTransferWroclaw()); }
public static DependencyResolver getInstance() { if (theResolver == null) { theResolver = new DependencyResolver(); } return theResolver; }
public void CanResolveDependencyByTypeAndName() { MockBuilderContext context = new MockBuilderContext(); object obj = new object(); context.Locator.Add(new DependencyResolutionLocatorKey(typeof(object), "Foo"), obj); DependencyResolver resolver = new DependencyResolver(context); Assert.AreSame(obj, resolver.Resolve(typeof(object), null, "Foo", NotPresentBehavior.ReturnNull, SearchMode.Local)); }
public void CanResolveDependency() { var resolver = new DependencyResolver(); resolver.Register<IFoo>(new Foo()); var foo = resolver.Resolve<IFoo>(); Assert.IsInstanceOfType(foo, typeof(Foo)); }
public void PublishMessageOnGetServices(DependencyResolver.GetServices sut, IAlternateMethodContext context) { context.Setup(c => c.Arguments).Returns(new object[] { typeof(string) }); context.Setup(c => c.ReturnValue).Returns(Enumerable.Empty<object>()); sut.NewImplementation(context); context.TimerStrategy().Verify(t => t.Time(It.IsAny<Action>())); context.MessageBroker.Verify(b => b.Publish(It.IsAny<DependencyResolver.GetServices.Message>())); }
public void ProceedWithRuntimePolicyOff(DependencyResolver.GetServices sut, IAlternateMethodContext context) { context.Setup(c => c.RuntimePolicyStrategy).Returns(() => RuntimePolicy.Off); sut.NewImplementation(context); context.Verify(c => c.Proceed()); context.Verify(c => c.Arguments, Times.Never()); context.Verify(c => c.ReturnValue, Times.Never()); }
public void TestMethod1() { var resolver = new DependencyResolver(); resolver.RegisterService<IJsonSerializer>(t => new JsonSerializer()); var serializer = resolver.GetService<IJsonSerializer>(); Assert.IsNotNull(serializer); }
public void testRecursiveResolveTransients() { DependencyResolver dependencyResolver = new DependencyResolver(); dependencyResolver.Register<ILogger, ConsoleLogger>(lifeStyleType.Transient); dependencyResolver.Register<ILoggerWrapper, LoggerWrapper>(lifeStyleType.Transient); ILoggerWrapper wrapper = dependencyResolver.Resolve<ILoggerWrapper>(); ILogger theLogger = dependencyResolver.Resolve<ILogger>(); Assert.IsTrue(wrapper.getWrappedLogger().getID() != theLogger.getID()); }
public void DefaultServiceLocatorBehaviorTests() { // Arrange var resolver = new DependencyResolver(); // Act & Assert Assert.IsNotNull(resolver.InnerCurrent.GetService<object>()); // Concrete type Assert.IsNull(resolver.InnerCurrent.GetService<ModelMetadataProvider>()); // Abstract type Assert.IsNull(resolver.InnerCurrent.GetService<IDisposable>()); // Interface Assert.IsNull(resolver.InnerCurrent.GetService(typeof(List<>))); // Open generic }
public void GetServices_IfTheTypeIsConcreteWithParameterlessConstructorAndIfTheTypeIsNotRegistered_ShouldReturnAnEmptyCollection() { TestHelper.ClearStructureMap(); TestHelper.AssertStructureMapIsCleared(); var instances = new DependencyResolver(ObjectFactory.Container).GetServices(typeof(SomeConcreteClassWithParameterlessConstructor)).ToArray(); Assert.IsNotNull(instances); Assert.IsFalse(instances.Any()); }
public static DependencyResolver Create() { var resolver = new DependencyResolver(); resolver.Register<IHubProxyFactory>(() => new HubProxyFactory()); var subscriptionStore = new Lazy<SubscriptionStore>(() => new SubscriptionStore()); resolver.Register<ISubscriptionStore>(() => subscriptionStore.Value); return resolver; }
public void ResolverCanCreateObjectWhenNotPresent() { MockBuilderContext context = CreateContext(); DependencyResolver resolver = new DependencyResolver(context); object obj = resolver.Resolve(typeof(object), null, null, NotPresentBehavior.CreateNew, SearchMode.Local); Assert.IsNotNull(obj); Assert.IsTrue(obj is object); }
public void ResolveShouldResolveParametersWithSpecifiedDependencyName() { var resolver = new DependencyResolver(); resolver.Register<IDummyToResolveParamter, DummyToResolveParameter2>(Lifetime.Default); resolver.Register<IDummyToResolveParamter, DummyToResolveParameter1>(Lifetime.Default, "depname"); var instance = resolver.Resolve<DummyToResolveWithParameters>(); Assert.IsInstanceOfType(instance.Param, typeof (DummyToResolveParameter1)); }
public AutoRouter(Router processor, Parser argParser, DependencyResolver resolver, bool debug) { m_logger = new CategoryLogger(this); m_processor = processor; m_taskResultLookup = new Dictionary<Type, PropertyInfo>(); m_argParser = argParser; m_resolver = resolver; m_debug = debug; CacheResultProperty(typeof(Task<object>)); }
public void DefaultServiceLocatorResolvesNewInstances() { // Arrange var resolver = new DependencyResolver(); // Act object obj1 = resolver.InnerCurrent.GetService<object>(); object obj2 = resolver.InnerCurrent.GetService<object>(); // Assert Assert.AreNotSame(obj1, obj2); }
public void ResolveShouldResolveParametersWithSpecifiedDependencyNameWithInstances() { var resolver = new DependencyResolver(); resolver.Register<IDummyToResolveParamter>(new DummyToResolveParameter2()); resolver.Register<IDummyToResolveParamter>(new DummyToResolveParameter1(), "depname"); var instance = resolver.Resolve<DummyToResolveWithParameters>(); Assert.IsInstanceOfType(instance.Param, typeof (DummyToResolveParameter1)); }
public void GetServices_IfTheTypeIsConcreteWithParameterlessConstructorAndIfTheTypeIsRegistered_ShouldReturnACollectionWithAnInstanceOfThatType() { TestHelper.ClearStructureMap(); TestHelper.AssertStructureMapIsCleared(); ObjectFactory.Initialize(initializer => initializer.For<SomeConcreteClassWithParameterlessConstructor>().Use<SomeConcreteClassWithParameterlessConstructor>()); var instances = new DependencyResolver(ObjectFactory.Container).GetServices(typeof(SomeConcreteClassWithParameterlessConstructor)).ToArray(); Assert.IsNotNull(instances); Assert.IsTrue(instances.Count() == 1); Assert.IsTrue(instances.ElementAt(0) is SomeConcreteClassWithParameterlessConstructor); }
/// <summary> /// Setup the dependency injection for controllers. /// </summary> private static void ConfigureDependencies(HttpConfiguration config) { var dependencyResolver = new DependencyResolver(); // create the service to be injected var customerDao = new CustomerDao(); // setup a constructor for a CustomersController dependencyResolver.RegisterType<CustomersController>(() => new CustomersController(customerDao)); // assign the resolver to the config config.DependencyResolver = dependencyResolver; }
public void ResolverPassesCallsToDelegateBasedResolver() { // Arrange var resolver = new DependencyResolver(); var mockResolver = new Mock<MockableResolver>(); resolver.InnerSetResolver(mockResolver.Object.Get, mockResolver.Object.GetAll); // Act & Assert resolver.InnerCurrent.GetService(typeof(object)); mockResolver.Verify(r => r.Get(typeof(object))); resolver.InnerCurrent.GetServices(typeof(string)); mockResolver.Verify(r => r.GetAll(typeof(string))); }
public void IocResolveTest() { var resolver = new DependencyResolver(); resolver.Register<IFoo>(new Foo()); resolver.Register<IBar>(new Bar()); Ioc.Initialise(resolver); var foo = Ioc.Resolve<IFoo>(); var bar = Ioc.Resolve<IBar>(); Assert.IsInstanceOfType(foo, typeof(IFoo)); Assert.IsInstanceOfType(bar, typeof(IBar)); }
public void ResolverUsesNamesToResolveDifferences() { MockBuilderContext context = new MockBuilderContext(); DependencyResolver resolver = new DependencyResolver(context); object obj1 = new object(); context.Locator.Add(new DependencyResolutionLocatorKey(typeof(object), null), obj1); object obj2 = new object(); context.Locator.Add(new DependencyResolutionLocatorKey(typeof(object), "Foo"), obj2); object obj3 = new object(); context.Locator.Add(new DependencyResolutionLocatorKey(typeof(object), "Bar"), obj3); Assert.AreSame(obj1, resolver.Resolve(typeof(object), null, null, NotPresentBehavior.ReturnNull, SearchMode.Local)); Assert.AreSame(obj2, resolver.Resolve(typeof(object), null, "Foo", NotPresentBehavior.ReturnNull, SearchMode.Local)); Assert.AreSame(obj3, resolver.Resolve(typeof(object), null, "Bar", NotPresentBehavior.ReturnNull, SearchMode.Local)); }
public void GuardClauses() { // Arrange var resolver = new DependencyResolver(); // Act & Assert Assert.ThrowsArgumentNull( () => resolver.InnerSetResolver((IDependencyResolver)null), "resolver"); Assert.ThrowsArgumentNull( () => resolver.InnerSetResolver((object)null), "commonServiceLocator"); Assert.ThrowsArgumentNull( () => resolver.InnerSetResolver(null, type => null), "getService"); Assert.ThrowsArgumentNull( () => resolver.InnerSetResolver(type => null, null), "getServices"); }
public static void SetUpIoC(HttpConfiguration config = null) { var container = new Container(); container.Configure(x => { x.AddRegistry<DefaultRegistry>(); x.AddRegistry<ControllerRegistry>(); }); // Register Service Locator Microsoft.Practices.ServiceLocation.ServiceLocator.SetLocatorProvider(() => new ServiceLocator(container)); // Register Dependency Resolver var resolver = new DependencyResolver(container); System.Web.Mvc.DependencyResolver.SetResolver(resolver); if (null != config) { config.DependencyResolver = resolver; config.Services.Replace(typeof(IHttpControllerActivator), new HttpControllerActivator(container)); } }
public void GuardClauses() { // Arrange var resolver = new DependencyResolver(); // Act & Assert ExceptionHelper.ExpectArgumentNullException( () => resolver.InnerSetResolver((IDependencyResolver)null), "resolver" ); ExceptionHelper.ExpectArgumentNullException( () => resolver.InnerSetResolver((object)null), "commonServiceLocator" ); ExceptionHelper.ExpectArgumentNullException( () => resolver.InnerSetResolver(null, type => null), "getService" ); ExceptionHelper.ExpectArgumentNullException( () => resolver.InnerSetResolver(type => null, null), "getServices" ); }
public static void RegisterComponents() { var container = new UnityContainer(); container.AddNewExtension <Interception>(); container.RegisterType <ExchangeConferenceRoomServiceConfiguration>(new HierarchicalLifetimeManager(), new InjectionFactory( c => CreateOrganizationalService(c, "Exchange", _ => new ExchangeConferenceRoomServiceConfiguration() { IgnoreFree = (bool)_.IgnoreFree.Value, ImpersonateForAllCalls = (bool)_.ImpersonateForAllCalls.Value, UseChangeNotification = (bool)_.UseChangeNotification.Value, EmailDomains = ((JArray)_.EmailDomains).Select(i => i.Value <string>()).ToArray(), }))); container.RegisterType <Func <ExchangeService> >(new HierarchicalLifetimeManager(), new InjectionFactory( c => CreateOrganizationalService(c, "Exchange", _ => ExchangeConferenceRoomService.GetExchangeServiceBuilder((string)_.Username.Value, (string)_.Password.Value, (string)_.ServiceUrl.Value)))); container.RegisterType <ISmsMessagingService>(new HierarchicalLifetimeManager(), new InjectionFactory( c => CreateOrganizationalService(c, "Plivo", _ => new SmsMessagingService((string)_.AuthId.Value, (string)_.AuthToken.Value, (string)_.From.Value)))); container.RegisterType <IGdoService>(new ContainerControlledLifetimeManager(), new InjectionFactory( c => CreateOrganizationalService(c, "GDO", _ => new GdoService(new Uri((string)_.BaseUrl.Value), (string)_.ApiKey.Value, (string)_.Username.Value, (string)_.Password.Value)))); container.RegisterType <IBroadcastService, SignalrBroadcastService>(new HierarchicalLifetimeManager()); container.RegisterType <IConnectionManager>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => GlobalHost.ConnectionManager)); container.RegisterType <IDateTimeService>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => new DateTimeService(TimeSpan.FromHours(0)))); container.RegisterType <HttpContextBase>(new HierarchicalLifetimeManager(), new InjectionFactory(c => new HttpContextWrapper(HttpContext.Current))); container.RegisterType <HttpRequestBase>(new HierarchicalLifetimeManager(), new InjectionFactory(c => c.Resolve <HttpContextBase>().Request)); container.RegisterType <ISmsAddressLookupService, SmsAddressLookupService>(new HierarchicalLifetimeManager()); container.RegisterType <ISignatureService, SignatureService>(new ContainerControlledLifetimeManager()); container.RegisterType <IMeetingCacheService, MeetingCacheService>(new ContainerControlledLifetimeManager()); // singleton cache container.RegisterType <ISimpleTimedCache, SimpleTimedCache>(new ContainerControlledLifetimeManager()); // singleton cache container.RegisterType <IContextService, ContextService>(new HierarchicalLifetimeManager()); container.RegisterType <IConferenceRoomDiscoveryService, ExchangeConferenceRoomDiscoveryService>(new HierarchicalLifetimeManager()); container.RegisterType <ITokenService, TokenService>(new HierarchicalLifetimeManager(), new InjectionFactory(c => new TokenService( ConfigurationManager.AppSettings["TokenIssuer"], ConfigurationManager.AppSettings["TokenAudience"], ConfigurationManager.AppSettings["TokenKey"], c.Resolve <OpenIdV1ConnectConfigurationService>(), c.Resolve <OpenIdV2ConnectConfigurationService>()))); container.RegisterType <OpenIdV1ConnectConfigurationService>(new ContainerControlledLifetimeManager()); container.RegisterType <OpenIdV2ConnectConfigurationService>(new ContainerControlledLifetimeManager()); container.RegisterType <CloudTableClient>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorage"]?.ConnectionString).CreateCloudTableClient() )); container.RegisterType <CachingBehavior>(new ContainerControlledLifetimeManager()); container.RegisterType <IDeviceStatusRepository, AzureTable.DeviceStatusRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IMeetingRepository, AzureTable.MeetingRepository>(new HierarchicalLifetimeManager()); container.RegisterType <IRoomMetadataRepository, AzureTable.RoomMetadataRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IFloorRepository, AzureTable.FloorRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IBuildingRepository, AzureTable.BuildingRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IDeviceRepository, AzureTable.DeviceRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IOrganizationRepository, AzureTable.OrganizationRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IOrganizationServiceConfigurationRepository, AzureTable.OrganizationServiceConfigurationRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IGlobalAdministratorRepository, AzureTable.GlobalAdministratorRepository>(new HierarchicalLifetimeManager(), new Interceptor <InterfaceInterceptor>(), new InterceptionBehavior <CachingBehavior>()); container.RegisterType <IIOCContainer, UnityIOCContainer>(new TransientLifetimeManager(), new InjectionFactory(c => new UnityIOCContainer(c, false))); container.RegisterType <ITokenProvider, HttpTokenProvider>(new HierarchicalLifetimeManager()); container.RegisterType <ExchangeRestWrapperFactoryCache, ExchangeRestWrapperFactoryCache>(new ContainerControlledLifetimeManager()); container.RegisterType <IExchangeServiceManager, ExchangeServiceManager>(new ContainerControlledLifetimeManager()); container.RegisterInstance(new MeetingCacheReloaderFactory(new UnityIOCContainer(container, false))); container.RegisterType <IExceptionHandler, SimpleExceptionHandler>(new ContainerControlledLifetimeManager()); if (false) { container.RegisterType <ISyncConferenceRoomService, ExchangeConferenceRoomService>(new HierarchicalLifetimeManager()); container.RegisterType <IConferenceRoomService, SyncConferenceRoomServiceWrapper>(new HierarchicalLifetimeManager()); // create change notifier in a child container and register as a singleton with the main container (avoids creating it's dependencies in the global container) var child = container.CreateChildContainer(); var changeNotificationService = child.Resolve <ExchangeEWSChangeNotificationService>(); container.RegisterInstance(typeof(IChangeNotificationService), changeNotificationService, new ContainerControlledLifetimeManager()); } else { container.RegisterType <ExchangeRestWrapperFactoryFactory>(new ContainerControlledLifetimeManager()); container.RegisterType <ExchangeRestWrapperFactoryFactory.ExchangeRestWrapperFactory>(new HierarchicalLifetimeManager(), new InjectionFactory( c => { var f = c.Resolve <ExchangeRestWrapperFactoryFactory>(); if (true) { return(CreateOrganizationalService(c, "Exchange", _ => f.GetFactory(null, (string)_.TenantId.Value, (string)_.ClientId.Value, (string)_.ClientCertificate.Value, (string)_.DefaultUser.Value))); } else { return(CreateOrganizationalService(c, "Exchange", _ => f.GetFactory(null, (string)_.ClientId.Value, (string)_.ClientSecret.Value, (string)_.Username.Value, (string)_.Password.Value, "me"))); } })); container.RegisterType <IConferenceRoomService, ExchangeRestConferenceRoomService>(new HierarchicalLifetimeManager()); container.RegisterType <ExchangeRestWrapper>(new HierarchicalLifetimeManager(), new InjectionFactory( c => { var svc = c.Resolve <ExchangeRestWrapperFactoryFactory.ExchangeRestWrapperFactory>(); return(System.Threading.Tasks.Task.Run(async() => await svc.CreateExchange()).Result); })); container.RegisterType <GraphRestWrapper>(new HierarchicalLifetimeManager(), new InjectionFactory( c => { var svc = c.Resolve <ExchangeRestWrapperFactoryFactory.ExchangeRestWrapperFactory>(); return(System.Threading.Tasks.Task.Run(async() => await svc.CreateGraph()).Result); })); // create change notifier in a child container and register as a singleton with the main container (avoids creating it's dependencies in the global container) var child = container.CreateChildContainer(); //var changeNotificationService = child.Resolve<ExchangeRestChangeNotificationService>(); //container.RegisterInstance(typeof(IExchangeRestChangeNotificationService), changeNotificationService, new ContainerControlledLifetimeManager()); child.RegisterType <ExchangePushChangeNotificationService>(new TransientLifetimeManager(), new InjectionFactory( c => { return(new ExchangePushChangeNotificationService(c.Resolve <IBroadcastService>(), c.Resolve <IMeetingCacheService>(), c.Resolve <IIOCContainer>(), ConfigurationManager.AppSettings["ServiceBusConnectionString"], ConfigurationManager.AppSettings["ServiceBusConnectionTopic"], ConfigurationManager.AppSettings["ServiceBusConnectionSubscription"])); })); var changeNotificationService = child.Resolve <ExchangePushChangeNotificationService>(); new System.Threading.Thread(changeNotificationService.RecieveMessages).Start(); container.RegisterInstance(typeof(IExchangeRestChangeNotificationService), changeNotificationService, new ContainerControlledLifetimeManager()); } // initialize all repositories in a child container (ie. create tables/etc.) { using (var c = container.CreateChildContainer()) { foreach (var r in new IRepository[] { c.Resolve <IMeetingRepository>(), c.Resolve <IRoomMetadataRepository>(), c.Resolve <IFloorRepository>(), c.Resolve <IBuildingRepository>(), c.Resolve <IDeviceRepository>(), c.Resolve <IOrganizationRepository>(), c.Resolve <IOrganizationServiceConfigurationRepository>(), c.Resolve <IGlobalAdministratorRepository>(), }) { r.Init(); } } } // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container)); }
/// <summary> /// Handles the global application startup event. /// </summary> protected void Application_Start() { // Create the tenant ID strategy. Required for multitenant integration. var tenantIdStrategy = new RequestParameterTenantIdentificationStrategy("tenant"); // Register application-level dependencies and controllers. Note that // we are manually registering controllers rather than all at the same // time because some of the controllers in this sample application // are for specific tenants. var builder = new ContainerBuilder(); builder.RegisterType <HomeController>(); builder.RegisterType <BaseDependency>().As <IDependency>(); // Adding the tenant ID strategy into the container so controllers // can display output about the current tenant. builder.RegisterInstance(tenantIdStrategy).As <ITenantIdentificationStrategy>(); // The service client is not different per tenant because // the service itself is multitenant - one client for all // the tenants and the service implementation switches. builder.Register(c => new ChannelFactory <IMultitenantService>(new BasicHttpBinding(), new EndpointAddress("http://localhost:63578/MultitenantService.svc"))).SingleInstance(); builder.Register(c => new ChannelFactory <IMetadataConsumer>(new WSHttpBinding(), new EndpointAddress("http://localhost:63578/MetadataConsumer.svc"))).SingleInstance(); // Register an endpoint behavior on the client channel factory that // will propagate the tenant ID across the wire in a message header. // On the service side, you'll need to read the header from incoming // message headers to reconstitute the incoming tenant ID. builder.Register(c => { var factory = c.Resolve <ChannelFactory <IMultitenantService> >(); factory.Opening += (sender, args) => factory.Endpoint.Behaviors.Add(new TenantPropagationBehavior <string>(tenantIdStrategy)); return(factory.CreateChannel()); }).InstancePerHttpRequest(); builder.Register(c => { var factory = c.Resolve <ChannelFactory <IMetadataConsumer> >(); factory.Opening += (sender, args) => factory.Endpoint.Behaviors.Add(new TenantPropagationBehavior <string>(tenantIdStrategy)); return(factory.CreateChannel()); }).InstancePerHttpRequest(); // Create the multitenant container based on the application // defaults - here's where the multitenant bits truly come into play. var mtc = new MultitenantContainer(tenantIdStrategy, builder.Build()); // Notice we configure tenant IDs as strings below because the tenant // identification strategy retrieves string values from the request // context. To use strongly-typed tenant IDs, create a custom tenant // identification strategy that returns the appropriate type. // Configure overrides for tenant 1 - dependencies, controllers, etc. mtc.ConfigureTenant("1", b => { b.RegisterType <Tenant1Dependency>().As <IDependency>().InstancePerDependency(); b.RegisterType <Tenant1Controller>().As <HomeController>(); }); // Configure overrides for tenant 2 - dependencies, controllers, etc. mtc.ConfigureTenant("2", b => { b.RegisterType <Tenant2Dependency>().As <IDependency>().SingleInstance(); b.RegisterType <Tenant2Controller>().As <HomeController>(); }); // Configure overrides for the default tenant. That means the default // tenant will have some different dependencies than other unconfigured // tenants. mtc.ConfigureTenant(null, b => b.RegisterType <DefaultTenantDependency>().As <IDependency>().SingleInstance()); // Create the dependency resolver using the // multitenant container instead of the application container. DependencyResolver.SetResolver(new AutofacDependencyResolver(mtc)); // Perform the standard MVC setup requirements. AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); }
public void Prepare() { //发起人 this._originator = DependencyResolver.Resolve <IUserService>().GetUserWhatever("houkun"); }
public static void RegisterAssembly() { _resolver = new NinjectHttpResolver(Assembly.GetExecutingAssembly()); //This is where the actual hookup to the Web API Pipeline is done. DependencyResolver.SetResolver(_resolver); }
public static void ContainerBuilderRegister() { //初始化AutoFac的相关功能 /* * 1.0 告诉AutoFac初始化数据仓储层FB.CMS.Repository.dll中所有类的对象实例。这些对象实例以其接口的形式保存在AutoFac容器中 * 2.0 告诉AutoFac初始化业务逻辑层FB.CMS.Services.dll中所有类的对象实例。这些对象实例以其接口的形式保存在AutoFac容器中 * 3.0 将MVC默认的控制器工厂替换成AutoFac的工厂 */ //第一步: 构造一个AutoFac的builder容器 ContainerBuilder builder = new Autofac.ContainerBuilder(); //第二步:告诉AutoFac控制器工厂,控制器类的创建去哪些程序集中查找(默认控制器工厂是去扫描bin目录下的所有程序集) //2.1 从当前运行的bin目录下加载FB.CMS.MvcSite.dll程序集 Assembly controllerAss = Assembly.Load("HelpYou.Component.Controllers"); //2.2 告诉AutoFac控制器工厂,控制器的创建从controllerAss中查找(注意:RegisterControllers()方法是一个可变参数,如果你的控制器类的创建需要去多个程序集中查找的话,那么我们就再用Assembly controllerBss=Assembly.Load("需要的程序集名")加载需要的程序集,然后与controllerAss组成数组,然后将这个数组传递到RegisterControllers()方法中) builder.RegisterControllers(controllerAss); //第三步:告诉AutoFac容器,创建项目中的指定类的对象实例,以接口的形式存储(其实就是创建数据仓储层与业务逻辑层这两个程序集中所有类的对象实例,然后以其接口的形式保存到AutoFac容器内存中,当然如果有需要也可以创建其他程序集的所有类的对象实例,这个只需要我们指定就可以了) //3.1 加载数据仓储层FB.CMS.Repository这个程序集。 Assembly repositoryAss = Assembly.Load("HelpYou.Component.Interface"); //3.2 反射扫描这个FB.CMS.Repository.dll程序集中所有的类,得到这个程序集中所有类的集合。 Type[] rtypes = repositoryAss.GetTypes(); //3.3 告诉AutoFac容器,创建rtypes这个集合中所有类的对象实例 builder.RegisterTypes(rtypes) .AsImplementedInterfaces(); //指明创建的rtypes这个集合中所有类的对象实例,以其接口的形式保存 //3.4 加载业务逻辑层FB.CMS.Services这个程序集。 Assembly servicesAss = Assembly.Load("HelpYou.Component.Service"); //3.5 反射扫描这个FB.CMS.Services.dll程序集中所有的类,得到这个程序集中所有类的集合。 Type[] stypes = servicesAss.GetTypes(); //3.6 告诉AutoFac容器,创建stypes这个集合中所有类的对象实例 builder.RegisterTypes(stypes) .AsImplementedInterfaces(); //指明创建的stypes这个集合中所有类的对象实例,以其接口的形式保存 //Type type = typeof(IHelpYou); //builder.RegisterType(type).AsImplementedInterfaces(); //第四步:创建一个真正的AutoFac的工作容器 var container1 = builder.Build(); //我们已经创建了指定程序集的所有类的对象实例,并以其接口的形式保存在AutoFac容器内存中了。那么我们怎么去拿它呢? //从AutoFac容器内部根据指定的接口获取其实现类的对象实例 //假设我要拿到IsysFunctionServices这个接口的实现类的对象实例,怎么拿呢? //var obj = container.Resolve<IsysFunctionServices>(); //只有有特殊需求的时候可以通过这样的形式来拿。一般情况下没有必要这样来拿,因为AutoFac会自动工作(即:会自动去类的带参数的构造函数中找与容器中key一致的参数类型,并将对象注入到类中,其实就是将对象赋值给构造函数的参数) //第五步:将当前容器中的控制器工厂替换掉MVC默认的控制器工厂。(即:不要MVC默认的控制器工厂了,用AutoFac容器中的控制器工厂替代)此处使用的是将AutoFac工作容器交给MVC底层 (需要using System.Web.Mvc;) DependencyResolver.SetResolver(new AutofacDependencyResolver(container1)); //我们知道控制器的创建是调用MVC默认的控制器工厂,默认的控制器工厂是调用控制器类的无参构造函数 //可是我们如果要使用AutoFac自动工厂,将对象通过构造函数注入类中,那么这个构造函数就需要带参数 //如果我们将控制器的无参构造函数删除,保留带参数的构造函数,MVC默认的控制器工厂来创建控制的时候 //就会去调用无参的构造函数,可是这时候发现没有无参的构造函数于是就报“没有为该对象定义无参数的构造函数”错误 //既然报错,那我们如果保留无参的构造函数,同时在声明一个带参数的构造函数是否可行呢? //答案;行是行,但是创建控制器的时候,MVC默认的控制器工厂调用的是无参构造函数,它并不会去调用有参的构造函数 //这时候,我们就只能将AutoFac它的控制器工厂替换调用MVC默认的控制器工厂(控制器由AutoFac的控制器工厂来创建) //而AutoFac控制器工厂在创建控制的时候只会扫描带参数的构造函数,并将对象注入到带参数的构造函数中 //AutofacDependencyResolver这个控制器工厂是继承了 IDependencyResolver接口的,而IDependencyResolver接口是MVC的东西 //MVC默认的控制器工厂名字叫:DefaultControllerFactory //具体参考:http://www.cnblogs.com/artech/archive/2012/04/01/controller-activation-032.html }
protected void Application_Start() { // workaroud для малоизвестного бага дотнета, от которого хренеют все 13 человек, что с ним столкнулись // эти две строчки должны стоять в начале AppStart // иначе MemoryCache работать не будет Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU"); SanitizeThreadCulture(); AreaRegistration.RegisterAllAreas(); IUnityContainer container = new UnityContainer(); RegisterControllers(container); var riExt = new ResolveInstancesExtension(typeof(CreateOnStartAttribute)); container.AddExtension(riExt); container.LoadConfiguration(); riExt.ResolveInstances(); ViewEngines.Engines.Add(new RoViewEngine()); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); WebApiConfig.Configure(GlobalConfiguration.Configuration, container); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); var uploadedFilesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UploadedFiles"); if (!Directory.Exists(uploadedFilesDirPath)) Directory.CreateDirectory(uploadedFilesDirPath); IEnumerable<Type> interfaces = AppDomain.CurrentDomain.GetAssemblies() .Where(x => x.GetName().Name.Contains(".Contract")) .Where(x => x.GetName().Name.Contains("RoCMS")) .SelectMany(x => x.GetExportedTypes().Where(y => y.IsInterface)); var services = AppDomain.CurrentDomain.GetAssemblies() .Where(x => x.GetName().Name.Contains(".Services")) .Where(x => x.GetName().Name.Contains("RoCMS")) .SelectMany(x => x.GetExportedTypes().Where(y => y.IsClass)); foreach (var interf in interfaces) { if (container.IsRegistered(interf)) { continue; } var cls = services.Where(x => interf.IsAssignableFrom(x)); if (cls.Count() == 1) { var cl = cls.Single(); container.RegisterType(interf, cl, null, new ContainerControlledLifetimeManager()); } } //var pluginTypes = from a in assemblies// from t in a.GetExportedTypes() // where typeof(IPlugin).IsAssignableFrom(t) // select t; // foreach (var t in pluginTypes) // container.RegisterType(typeof(IPlugin), t); RouteConfig.RegisterRedirects(RouteTable.Routes); ConfigureModules(BundleTable.Bundles, GlobalConfiguration.Configuration, GlobalFilters.Filters, RouteTable.Routes); RouteConfig.RegisterRoutes(RouteTable.Routes); RegisterSearch(); var webConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); try { foreach(ConnectionStringSettings cstr in webConfiguration.ConnectionStrings.ConnectionStrings) { // если есть BasicConnection, значит, RoCMS установлена IsInstalled |= cstr.Name.Equals("BasicConnection"); if (IsInstalled) break; } } catch (Exception e) { if (DemoMode) { IsInstalled = true; } else { IsInstalled = false; } } }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder()); }
private static void BootstrapContainer() { IUnityContainer unityContainer = IoCContainerAccessor.GetInstance(); DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer)); }
public static void RestartApplication() { var applicationLifetime = DependencyResolver.Resolve <IApplicationLifetime>(); applicationLifetime.StopApplication(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #region Autofac在MVC中注册 ContainerBuilder builder = new ContainerBuilder(); var service = Assembly.Load("IService"); var service1 = Assembly.Load("Service"); var service2 = Assembly.Load("Model"); Assembly[] assemblyArr = new Assembly[] { service, service1, service2 }; builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(assemblyArr).AsImplementedInterfaces(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion #region 添加初始数据 DbContext db = new MyContext(); if (db.Database.CreateIfNotExists()) { //前台权限 IAuthorityWebService authorityService = new AuthorityWebService(); List <AuthorityModel> authorityList = new List <AuthorityModel>() { new AuthorityModel() { BuildTime = DateTime.Now, Description = "读博客的权限", Name = "读权限", State = 1, Type = 1, UpdateTime = DateTime.Now, RoleModels = new List <RoleModel>() }, new AuthorityModel() { BuildTime = DateTime.Now, Description = "写博客的权限", Name = "写权限", State = 1, Type = 1, UpdateTime = DateTime.Now, RoleModels = new List <RoleModel>() } }; authorityService.AddRange(authorityList); AuthorityModel authority1 = new AuthorityModel(); authority1 = authorityService.GetList(s => s.Name == "读权限" && s.State == 1).ToList().FirstOrDefault(); //前台角色 IRoleWebService roleService = new RoleWebService(); List <RoleModel> roleList = new List <RoleModel>() { new RoleModel() { BuildTime = DateTime.Now, Description = "一般用户", RoleName = "普通用户", State = 1, UpdateTime = DateTime.Now, AuthorityModels = new List <AuthorityModel>(), UserModels = new List <UserModel>() }, new RoleModel() { BuildTime = DateTime.Now, Description = "充值的用户拥有更多权限", RoleName = "VIP用户", State = 1, UpdateTime = DateTime.Now, AuthorityModels = new List <AuthorityModel>(), UserModels = new List <UserModel>() } }; roleService.AddRange(roleList); var role1 = roleService.GetList(s => s.RoleName == "普通用户" && s.State == 1).ToList().FirstOrDefault(); var role2 = roleService.GetList(s => s.RoleName == "VIP用户" && s.State == 1).ToList().FirstOrDefault(); role1.AuthorityModels.Add(authority1); role2.AuthorityModels.Add(authority1); roleService.Update(role1); roleService.Update(role2); //用户数据 IUserWebService userService = new UserWebService(); List <UserModel> userList = new List <UserModel>() { new UserModel() { BuildTime = DateTime.Now, Count = 0, EMail = "*****@*****.**", HeadPicUrl = "~/Imgs/HeadPic/headpic-1.jpg", LoginTime = DateTime.Now, Type = 1, Pwd = Common.EncryptionHelper.GetMd5Str("112233"), State = 1, TelNumber = "155555555", Name = "MrChen", UpdateTime = DateTime.Now, Role = role1 }, new UserModel() { BuildTime = DateTime.Now, Count = 0, EMail = "*****@*****.**", HeadPicUrl = "~/Imgs/HeadPic/headpic-2.jpg", LoginTime = DateTime.Now, Type = 2, Pwd = Common.EncryptionHelper.GetMd5Str("112233"), State = 1, TelNumber = "155555555", Name = "MrSong", UpdateTime = DateTime.Now, Role = role2 } }; userService.AddRange(userList); UserModel user11 = new UserModel(); user11 = userService.GetList(s => s.Id == 1).ToList().FirstOrDefault(); //博客类型 IBlogTypeWebService blogTypeService = new BlogTypeWebService(); List <BlogTypes> typeList = new List <BlogTypes>() { new BlogTypes() { CreateTime = DateTime.Now, State = 1, TypeName = "类型1", UpdateTmie = DateTime.Now, BlogArticles = new List <BlogArticle>() }, new BlogTypes() { CreateTime = DateTime.Now, State = 1, TypeName = "类型2", UpdateTmie = DateTime.Now, BlogArticles = new List <BlogArticle>() }, }; blogTypeService.AddRange(typeList); var type1 = blogTypeService.GetList(s => s.Id == 1).ToList().FirstOrDefault(); var type2 = blogTypeService.GetList(s => s.Id == 2).ToList().FirstOrDefault(); BlogTypes type11 = new BlogTypes(); type11 = type1; BlogTypes type22 = new BlogTypes(); type22 = type2; //博客文章 IBlogArticleWebService blogArticleService = new BlogArticleWebService(); List <BlogArticle> articleList = new List <BlogArticle>() { new BlogArticle() { Address = "1313", Content = "1211122212", CreateTime = DateTime.Now, State = 1, Title = "测试1", UpdateTime = DateTime.Now, WatchCount = 1, ZanCount = 0, BlogComments = new List <BlogComment>(), Type = type11, Summary = "aaa" }, new BlogArticle() { Address = "1312", Content = "1211122212", CreateTime = DateTime.Now, State = 1, Title = "测试2", UpdateTime = DateTime.Now, WatchCount = 1, ZanCount = 0, BlogComments = new List <BlogComment>(), Type = type22, Summary = "bbb" } }; blogArticleService.AddRange(articleList); BlogArticle article1 = new BlogArticle(); article1 = blogArticleService.GetList(s => s.Id == 1).ToList().FirstOrDefault(); //博客评论 IBlogCommentWebService blogCommentService = new BlogCommentWebService(); List <BlogComment> commentList = new List <BlogComment>() { new BlogComment() { Content = "你好啊", UpdateTime = DateTime.Now, State = 1, CommentId = 0, BlogArticle = article1, User = user11, CreateTime = DateTime.Now }, new BlogComment() { Content = "你好啊", UpdateTime = DateTime.Now, State = 1, CommentId = 1, BlogArticle = article1, User = user11, CreateTime = DateTime.Now }, }; blogCommentService.AddRange(commentList); //管理员数据 IAdminUserService adminUserService = new AdminUserService(); List <AdminUser> adminUserList = new List <AdminUser>() { new AdminUser() { BuildTime = DateTime.Now, Name = "sbk", LoginTime = DateTime.Now, Password = Common.EncryptionHelper.GetMd5Str("abc112233"), State = 1, TelNumber = "18251935175", Type = 1 }, new AdminUser() { BuildTime = DateTime.Now, Name = "admin", LoginTime = DateTime.Now, Password = Common.EncryptionHelper.GetMd5Str("abc112233"), State = 1, TelNumber = "18251935175", Type = 1 } }; adminUserService.AddRange(adminUserList); //后台权限数据 IAdminAuthorityService adminAuthorityService = new AdminAuthorityService(); List <AdminAuthority> adminAuthorityList = new List <AdminAuthority>() { new AdminAuthority() { BuildTime = DateTime.Now, Description = "用于读取基本信息的权限", Name = "读权限", State = 1, Type = 1 }, new AdminAuthority() { BuildTime = DateTime.Now, Description = "用于写入基本信息的权限", Name = "写权限", State = 1, Type = 1 } }; adminAuthorityService.AddRange(adminAuthorityList); //后台角色数据 IAdminRoleService adminRoleService = new AdminRoleService(); List <AdminRole> adminRoleList = new List <AdminRole>() { new AdminRole() { BuildTime = DateTime.Now, Description = "管理单个项目", RoleName = "S级管理员", State = 1 }, new AdminRole() { BuildTime = DateTime.Now, Description = "管理单个项目", RoleName = "SS级管理员", State = 1 } }; adminRoleService.AddRange(adminRoleList); } #endregion //log4net.Config.XmlConfigurator.Configure();//读取Log4Net配置信息 //MiniProfilerEF6.Initialize();//注册MiniProfiler,网页性能插件 log4net.Config.XmlConfigurator.Configure(); //WaitCallback ThreadPool.QueueUserWorkItem((a) => { while (true) { if (MyExceptionAttribute.ExceptionQueue.Count > 0) { Exception ex = MyExceptionAttribute.ExceptionQueue.Dequeue();//出队 //string fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt"; //File.AppendAllText(fileLogPath + fileName, ex.ToString(), System.Text.Encoding.Default); //ILog logger = LogManager.GetLogger("errorMsg"); ILog logger = log4net.LogManager.GetLogger("logger"); logger.Error(ex.ToString()); #region 发送邮件 //MailHelper mail = new MailHelper(); //mail.MailServer = "smtp.qq.com"; //mail.MailboxName = "*****@*****.**"; //mail.MailboxPassword = "******";//开启QQ邮箱POP3/SMTP服务时给的授权码 ////操作打开QQ邮箱->在账号下方点击"设置"->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 ////obxxsfowztbideee为2872845261@qq的授权码 //mail.MailName = "Error"; //try //{ // mail.Send("*****@*****.**", "Error", ex.ToString()); //} //catch //{ } #endregion } else { Thread.Sleep(3000);//如果队列中没有数据,则休息为了避免占用CPU的资源. } } }); }
public static async Task OnAccessTokenRefresh(string newAccessToken) { await DependencyResolver.Resolve <IDataStorageService>().StoreAccessTokenAsync(newAccessToken); }
public static async Task OnSessionTimeout() { await DependencyResolver.Resolve <IAccountService>().LogoutAsync(); }
private void Awake() { _paddleController = DependencyResolver.GetPaddleController(_paddleControllerParameters); }
public static void Main(string[] args) { Console.WriteLine("----------DotNetCoreSample----------"); // var dataLogger = LogHelper.GetLogger(typeof(DataExtension)); // DataExtension.CommandLogAction = msg => dataLogger.Debug(msg); //AspectTest.ServiceContainerTest(); //ProcessExecutorTest.RawProcessTest(); //ProcessExecutorTest.DotNetInfoTest(); // ProcessExecutorTest.DotNetNugetGlobalPackagesInfoTest(); //LoggerTest.MainTest(); LoggerTest.MicrosoftLoggingTest(); Console.ReadLine(); var services = new ServiceCollection(); services.AddTransient <IFly, MonkeyKing>(); IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var city = configuration.GetAppSetting("City"); var number = configuration.GetAppSetting <int>("Number"); Console.WriteLine($"City:{city}, Number:{number}"); services.AddSingleton(configuration); //services.AddSingleton<IEventStore, EventStoreInMemory>(); //services.AddSingleton<IEventBus, EventBus>(); //services.AddSingleton(DelegateEventHandler.FromAction<CounterEvent>(@event => // LogHelper.GetLogger(typeof(DelegateEventHandler<CounterEvent>)) // .Info($"Event Info: {@event.ToJson()}") // ) //); services.AddSingletonProxy <IFly, MonkeyKing>(); Action <DbContextOptionsBuilder> dbContextOptionsAction = options => { options.UseInMemoryDatabase("Test"); }; services.AddDbContext <TestDbContext>(dbContextOptionsAction); services.AddScopedProxy <TestDbContext>(); services.AddEvents(); services.AddSingletonProxy <IEventBus, EventBus>(); services.AddFluentAspects(options => { options.NoInterceptPropertyGetter <IFly>(f => f.Name); options.InterceptAll() .With <LogInterceptor>() ; options.InterceptMethod <DbContext>(x => x.Name == nameof(DbContext.SaveChanges) || x.Name == nameof(DbContext.SaveChangesAsync)) .With <DbContextSaveInterceptor>() ; options.InterceptMethod <IFly>(f => f.Fly()) .With <LogInterceptor>(); options.InterceptType <IFly>() .With <LogInterceptor>(); options .WithProperty("TraceId", "121212") ; }) // .UseCastleProxy() // .UseAspectCoreProxy() ; DependencyResolver.SetDependencyResolver(services); //var fly = DependencyResolver.ResolveService<IFly>(); //Console.WriteLine(fly.Name); //fly.Fly(); //fly.OpenFly<int>(); //fly.OpenFly<string>(); //fly.FlyAway(); //var animal1 = FluentAspects.AspectOptions.ProxyFactory.CreateInterfaceProxy<IAnimal<int>>(); //animal1.Eat(); //var animal2 = FluentAspects.AspectOptions.ProxyFactory.CreateInterfaceProxy<IAnimal<string>>(); //animal2.Eat(); //var animal = FluentAspects.AspectOptions.ProxyFactory.CreateProxy<Animal<string>>(); //animal.Eat(); //animal.Eat(); //Console.WriteLine(animal.GetEatCount()); //animal.Drink("xxx"); //Console.WriteLine(animal.GetDrinkCount()); //animal = FluentAspects.AspectOptions.ProxyFactory.CreateProxyWithTarget<Animal<string>>(new Animal<string>()); //animal.Eat(); //animal.Eat(); //Console.WriteLine(animal.GetEatCount()); //animal.Drink("xxx"); //Console.WriteLine(animal.GetDrinkCount()); //DependencyResolver.TryInvokeService<TestDbContext>(dbContext => //{ // dbContext.TestEntities.Add(new TestEntity() { Token = "sasa", CreatedTime = DateTime.Now, }); // var hasChanges = dbContext.ChangeTracker.HasChanges(); // Console.WriteLine($"hasChanges:{hasChanges}"); // dbContext.SaveChanges(); //}); //DependencyResolver.TryInvokeService<IEventBus>(eventBus => //{ // eventBus.Publish(new CounterEvent()); //}); DependencyResolver.TryInvoke <IProxyFactory>(proxyFactory => { var counterEvent = new CounterEvent() { Counter = 1 }; var eventBusProxy = proxyFactory.CreateProxy <IEventBus, EventBus>(); eventBusProxy.Publish(counterEvent); var handlerProxy = proxyFactory.CreateProxyWithTarget <IEventHandler <CounterEvent> >(DelegateEventHandler.FromAction <CounterEvent>(e => { Console.WriteLine(e.ToJson()); })); handlerProxy.Handle(counterEvent) .GetAwaiter().GetResult(); }); //DependencyResolver.TryInvokeServiceAsync<TestDbContext>(dbContext => //{ // dbContext.TestEntities.Add(new TestEntity() { Token = "sasa", CreatedTime = DateTime.Now, }); // if (dbContext.ChangeTracker is null) // { // Console.WriteLine($"{nameof(dbContext.ChangeTracker)} is null ..."); // } // else // { // foreach (var entry in dbContext.ChangeTracker.Entries<TestEntity>()) // { // Console.WriteLine(entry.Entity.Token); // } // } // if (dbContext.Database is null) // { // Console.WriteLine($"{nameof(dbContext.Database)} is null ..."); // } // if (dbContext.Database is null) // { // Console.WriteLine($"{nameof(dbContext.Database)} is null ..."); // } // return dbContext.SaveChangesAsync(); //}); //DependencyResolver.ResolveRequiredService<IFly>() // .Fly(); //DependencyInjectionTest.Test(); // EventTest.MainTest(); // SerilogTest.MainTest(); //var builder = new ContainerBuilder(); //builder.RegisterType<MonkeyKing>().As<IFly>(); //DependencyResolver.SetDependencyResolver((IServiceProvider)new AutofacDependencyResolver(builder.Build())); //DependencyInjectionTest.Test(); //int a = 1; //Console.WriteLine(JsonConvert.SerializeObject(a));// output 1 //var pagedListModel = new PagedListModel<int>() //{ // PageNumber = 1, // PageSize = 4, // TotalCount = 10, // Data = new[] { 1, 2, 3, 4 } //}; //Console.WriteLine(pagedListModel.ToJson()); // log test // LoggerTest.MainTest(); // Log4NetTest.MainTest(); //ILoggerFactory loggerFactory = new LoggerFactory(); //loggerFactory.AddConsole(); //loggerFactory.AddDebug(); //loggerFactory.AddDelegateLogger( // (category, logLevel, exception, msg) => // { // Console.WriteLine($"{category}:[{logLevel}] {msg}\n{exception}"); // } //); //var logger = new Logger<Program>(loggerFactory); //logger.LogInformation("Logging information from Microsoft.Extensions.Logging"); //InvokeHelper.TryInvoke(DataExtensionTest.MainTest); //TaskTest.TaskWhenAllTest().GetAwaiter().GetResult(); //Base64UrlEncodeTest.MainTest(); //var a = new { Name = "2123" }; //var name = a.GetProperty("Name").GetValueGetter().Invoke(a); //Console.WriteLine(name); //var structTest = new TestStruct() { Name = "1233" }; //var obj = (object)structTest; //Console.WriteLine(structTest.GetProperty("Name").GetValueGetter<TestStruct>().Invoke(structTest)); //structTest.GetProperty("Name").GetValueSetter().Invoke(obj, "Name1"); //structTest = (TestStruct)obj; //Console.WriteLine(structTest.Name); //Expression<Func<TestEntity, bool>> exp = t => t.Id > 10 && t.Token == "123" && t.Token.Contains("12"); //var str = SqlExpressionParser.ParseExpression(exp); //Console.WriteLine("sql: {0}", str); //exp = t => true; //str = SqlExpressionParser.ParseExpression(exp); //Console.WriteLine("sql: {0}", str); //RepositoryTest.MainTest(); //var securityToken = ApplicationHelper.ApplicationName + "_test_123"; //var code123 = TotpHelper.GenerateCode(securityToken); //Console.WriteLine(code123); //var result = TotpHelper.ValidateCode(securityToken, code123); //Console.WriteLine($"validate result: {result}"); //var ttl = 2; //while (ttl > 1) //{ // ttl = TotpHelper.TTL(securityToken); // Console.WriteLine($"Current ttl: {ttl}, newId: {ObjectIdGenerator.Instance.NewId()}"); // Thread.Sleep(1000); //} //result = TotpHelper.ValidateCode(securityToken, code123); //Console.WriteLine($"validate result1: {result}"); //result = TotpHelper.ValidateCode(securityToken, code123, 60); //Console.WriteLine($"validate result2: {result}"); //var code1234 = TotpHelper.GenerateCode(ApplicationHelper.ApplicationName + "test_1234"); //Console.WriteLine(code1234); // InvokeHelper.TryInvoke(HttpRequesterTest.MainTest); //var pagedListModel = new PagedListModel<int>() //{ // PageNumber = 2, PageSize = 2, TotalCount = 6, Data = new int[] {1, 2}, //}; //var pagedListModel1 = new PagedListModel1<int>() //{ // PageNumber = 2, // PageSize = 2, // TotalCount = 6, // Data = new int[] { 1, 2 }, //}; //Console.WriteLine($"pagedListModel:{JsonConvert.SerializeObject(pagedListModel)}, pagedListModel1:{JsonConvert.SerializeObject(pagedListModel1)}"); //var posts = new[] { new { PostId = 1, PostTitle = "12333", }, new { PostId = 2, PostTitle = "12333", }, }; //var postTags = new[] { new { PostId = 1, Tag = "HHH" } }; //var result = posts.LeftJoin(postTags, p => p.PostId, pt => pt.PostId, (p, pt) => new { p.PostId, p.PostTitle, pt?.Tag }).ToArray(); //Console.WriteLine(result.ToJson()); // CronHelperTest.MainTest(); // DependencyInjectionTest.BuiltInIocTest(); //Expression<Func<TestEntity, bool>> expression = // t => t.Id > 0 && t.CreatedTime < DateTime.Now && t.Token == null; //var visitor = new SqlExpressionVisitor(null); //visitor.Visit(expression); //Console.WriteLine(visitor.GetCondition()); //PipelineTest.TestV2(); //PipelineTest.AsyncPipelineBuilderTestV2().Wait(); Console.ReadLine(); }
public void ResolverWillCreateOnceAndReturnExistingSubsequentlyForCreateFlag() { MockBuilderContext context = CreateContext(); DependencyResolver resolver = new DependencyResolver(context); object obj1 = resolver.Resolve(typeof(object), null, null, NotPresentBehavior.CreateNew, SearchMode.Local); object obj2 = resolver.Resolve(typeof(object), null, null, NotPresentBehavior.CreateNew, SearchMode.Local); Assert.IsNotNull(obj1); Assert.AreSame(obj1, obj2); }
/// <summary> /// from http://stackoverflow.com/questions/21614253/how-do-i-properly-register-autofac-in-a-basic-mvc5-1-website /// For more info see /// :https://code.google.com/p/autofac/wiki/MvcIntegration (mvc4 instructions) /// </summary> public static void RegisterDependencies() { #region Create the builder var builder = new ContainerBuilder(); #endregion #region Setup a common pattern // placed here before RegisterControllers as last one wins builder.RegisterAssemblyTypes() .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces() .InstancePerHttpRequest(); builder.RegisterAssemblyTypes() .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces() .InstancePerHttpRequest(); #endregion #region Register all controllers for the assembly // Note that ASP.NET MVC requests controllers by their concrete types, // so registering them As<IController>() is incorrect. // Also, if you register controllers manually and choose to specify // lifetimes, you must register them as InstancePerDependency() or // InstancePerHttpRequest() - ASP.NET MVC will throw an exception if // you try to reuse a controller instance for multiple requests. builder.RegisterControllers(typeof(MvcApplication).Assembly) .InstancePerHttpRequest(); #endregion #region Register modules builder.RegisterAssemblyModules(typeof(MvcApplication).Assembly); builder.RegisterAssemblyModules(typeof(RegisterApplicationIoC).Assembly); #endregion #region Model binder providers - excluded - not sure if need //builder.RegisterModelBinders(Assembly.GetExecutingAssembly()); //builder.RegisterModelBinderProvider(); #endregion #region Inject HTTP Abstractions /* * The MVC Integration includes an Autofac module that will add HTTP request * lifetime scoped registrations for the HTTP abstraction classes. The * following abstract classes are included: * -- HttpContextBase * -- HttpRequestBase * -- HttpResponseBase * -- HttpServerUtilityBase * -- HttpSessionStateBase * -- HttpApplicationStateBase * -- HttpBrowserCapabilitiesBase * -- HttpCachePolicyBase * -- VirtualPathProvider * * To use these abstractions add the AutofacWebTypesModule to the container * using the standard RegisterModule method. */ builder.RegisterModule <AutofacWebTypesModule>(); #endregion #region Set the MVC dependency resolver to use Autofac var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion }
public static void RegisterDependencies() { // Cant put credentials on GitHub so segregated them into excluded JSON file var settings = new Domain.Settings(new Repository.SettingsRepository <Settings>()).GetSettings( HttpContext.Current.Server.MapPath(@"~/App_Data/Settings.json")); var builder = new ContainerBuilder(); // Register API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // Register MVC controllers. builder.RegisterControllers(typeof(MvcApplication).Assembly); builder.RegisterType <Domain.RedAlert>().As <Domain.IRedAlert>(); builder.RegisterType <Domain.Screens>().As <Domain.IScreens>(); builder.RegisterType <Domain.Environments>().As <Domain.IEnvironments>(); builder.RegisterType <Domain.Builds>().As <Domain.IBuilds>(); builder.RegisterType <Domain.Deployments>().As <Domain.IDeployments>(); builder.RegisterType <Domain.Issues>().As <Domain.IIssues>(); builder.RegisterType <Domain.GitHub>().As <Domain.IGitHub>(); builder.RegisterType <Domain.Settings>().As <Domain.ISettings>(); builder.RegisterType <Services.Builds>() .As <Services.IBuilds>() .WithParameter("domain", settings.BuildServerDomain) .WithParameter("username", settings.BuildServerUsername) .WithParameter("password", settings.BuildServerPassword); builder.RegisterType <Services.Deployments>() .As <Services.IDeployments>() .WithParameter("deploymentServer", settings.DeploymentServerPath) .WithParameter("apiKey", settings.DeploymentServerKey); builder.RegisterType <Services.Issues>() .As <Services.IIssues>() .WithParameter("url", settings.IssuesUrl) .WithParameter("username", settings.IssuesUsername) .WithParameter("password", settings.IssuesPassword); builder.RegisterType <Services.GitHub <Models.GitHub.Branch> >() .As <Services.IGitHub <Models.GitHub.Branch> >() .WithParameter("username", settings.GitHubUsername) .WithParameter("password", settings.GitHubPassword); builder.RegisterType <Services.GitHub <Models.GitHub.PullRequest> >() .As <Services.IGitHub <Models.GitHub.PullRequest> >() .WithParameter("username", settings.GitHubUsername) .WithParameter("password", settings.GitHubPassword); builder.RegisterType <Services.GitHub <Models.GitHub.Comment> >() .As <Services.IGitHub <Models.GitHub.Comment> >() .WithParameter("username", settings.GitHubUsername) .WithParameter("password", settings.GitHubPassword); builder.RegisterType <Repository.SettingsRepository <RedAlert> >().As <Repository.IRepository <RedAlert> >(); builder.RegisterType <Repository.SettingsRepository <Screen> >().As <Repository.IRepository <Screen> >(); builder.RegisterType <Repository.SettingsRepository <Tenant> >().As <Repository.IRepository <Tenant> >(); builder.RegisterType <Repository.SettingsRepository <BuildProject> >().As <Repository.IRepository <BuildProject> >(); builder.RegisterType <Repository.SettingsRepository <Query> >().As <Repository.IRepository <Query> >(); builder.RegisterType <Repository.SettingsRepository <Models.Deployments.Environment> >().As <Repository.IRepository <Models.Deployments.Environment> >(); builder.RegisterType <Repository.SettingsRepository <Models.GitHub.Settings> >().As <Repository.IRepository <Models.GitHub.Settings> >(); builder.RegisterType <Repository.SettingsRepository <Settings> >().As <Repository.IRepository <Settings> >(); // Set the dependency resolver to be Autofac. var container = builder.Build(); // Get HttpConfiguration. var config = GlobalConfiguration.Configuration; // Web API dependency resolver config.DependencyResolver = new AutofacWebApiDependencyResolver(container); // MVC dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
// For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromDays(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromDays(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); var builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest(); builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest(); builder.RegisterType <CucDiSanDbContext>().AsSelf().InstancePerRequest(); // Repositories builder.RegisterAssemblyTypes(typeof(ActionLogRepository).Assembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces().InstancePerRequest(); // Services builder.RegisterAssemblyTypes(typeof(IActionLogServices).Assembly) .Where(t => t.Name.EndsWith("Services")) .AsImplementedInterfaces().InstancePerRequest(); Autofac.IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public EntityCollectionTests() { DependencyResolver.Clear(); }
private static void RegisterServices(IKernel kernel) { DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel)); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer <ApplicationDbContext>(null); #region Autofac DI Configurations // create an autofac container builder ContainerBuilder builder = new ContainerBuilder(); // Register MVC controllers (MvcApplication is the name of the class in Global.asax.) builder.RegisterControllers(typeof(MvcApplication).Assembly).InstancePerLifetimeScope(); // manual registration of types and services; builder.RegisterType <ApplicationDbContext>().InstancePerLifetimeScope(); builder.RegisterType <EFUnitOfWork>() .As <IUnitOfWork>() //.WithParameter(new TypedParameter(typeof(ApplicationDbContext), new ApplicationDbContext())) .InstancePerRequest(); builder.RegisterType <SongRepository>() .As <ISongRepostiory>() //.WithParameter(new TypedParameter(typeof(ApplicationDbContext), new ApplicationDbContext())) .InstancePerRequest(); /* builder.RegisterAssemblyTypes(typeof(Song).Assembly) * .Where(type => type.Name.EndsWith("Repository")) * .As(type => type.GetInterfaces()?.FirstOrDefault( * interfaceType => interfaceType.Name.Equals("I" + type.Name))) * .InstancePerRequest() * .WithParameter(new TypedParameter(typeof(ApplicationDbContext), new ApplicationDbContext()));*/ // OPTIONAL: Register model binders that require DI. builder.RegisterModelBinders(typeof(MvcApplication).Assembly); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. builder.RegisterModule <AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters. builder.RegisterFilterProvider(); // OPTIONAL: Enable action method parameter injection (RARE). //builder.InjectActionInvoker(); // For property injection using Autofac // builder.RegisterType<TheRequestedService>().PropertiesAutowired(); // build the dependencies container IContainer container = builder.Build(); // Replqde the default ASP.NET MVC dependency resolver to Autofac's dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion }
/// <summary> /// 负责调用autofac实现依赖注入,负责创建MVC控制器类的对象(调用控制器的有参构造函数),接管DefaultControllerFactory的工作 /// </summary> public static void Register() { // 第一步:注册控制器 var builder = new ContainerBuilder(); // 告诉autofac将来要创建的控制器类存放在哪个程序集 //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(PropertyWiringOptions.PreserveSetValues); // 把当前程序集中的 Controller 都注册 builder.RegisterControllers(typeof(MvcApplication).Assembly) // 自动给属性进行“注入” .PropertiesAutowired(PropertyWiringOptions.PreserveSetValues); builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterFilterProvider(); // 第二步:注册接口 // 获取所有相关类库的程序集 Assembly[] repository_assemblies = new Assembly[] { Assembly.Load(Assemblies.RepositoryAssembly) }; // 把当前程序集中的类都注册 builder.RegisterAssemblyTypes(repository_assemblies) // 注入类本身 .AsSelf() // 剔除抽象类; type1.IsAssignableFrom(type2):type2是否实现了type1的接口/或者是否集成自type1。这样就只注册实现了IBaseService接口的类,避免注册其它无关的类 .Where(type => !type.IsAbstract) // 为接口注入具体类 .AsImplementedInterfaces() // 自动给属性进行“注入” .PropertiesAutowired() // 同一个Lifetime生成的对象是同一个实例 .InstancePerLifetimeScope(); // 获取所有相关类库的程序集 Assembly[] service_assemblies = new Assembly[] { Assembly.Load(Assemblies.ServiceAssembly) }; // 把当前程序集中的类都注册 builder.RegisterAssemblyTypes(service_assemblies) // 剔除抽象类; type1.IsAssignableFrom(type2):type2是否实现了type1的接口/或者是否集成自type1。这样就只注册实现了IBaseService接口的类,避免注册其它无关的类 .Where(type => !type.IsAbstract) // 注入类本身 .AsSelf() // 为接口注入具体类 .AsImplementedInterfaces() // 自动给属性进行“注入” .PropertiesAutowired() // 同一个Lifetime生成的对象是同一个实例 .InstancePerLifetimeScope(); // 其他 builder.RegisterType <DefaultDbContext>().OnRelease(db => db.Dispose()).InstancePerLifetimeScope(); builder.RegisterType <RedisHelper>().OnRelease(db => db.Dispose()).InstancePerLifetimeScope(); //builder.RegisterType<BackgroundJobClient>().SingleInstance();//指定生命周期为单例 //builder.RegisterType<HangfireBackJob>().As<IHangfireBackJob>().PropertiesAutowired(PropertyWiringOptions.PreserveSetValues).InstancePerDependency(); // 支付平台 builder.Register(a => { var gateways = new Gateways(); #region gateways.RegisterAlipay(); //gateways.RegisterAlipay(); var alipayMerchant = new PaySharp.Alipay.Merchant { AppId = "2016081600256163", NotifyUrl = "http://localhost:50160/Notify", ReturnUrl = "http://localhost:50160/Notify", AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsW6+mN2E3Oji2DPjSKuYgRzK6MlH9q6W0iM0Yk3R0qbpp5wSesSXqudr2K25gIBOTCchiIbXO7GXt/zEdnhnC32eOaTnonDsnuBWIp+q7LoVx/gvKIX5LTHistCvGli8VW4EDGsu2jAyQXyMPgPrIz+/NzWis/gZsa4TaqVY4SpWRuSgMXxleh2ERB6k0ijK0IYM+Cv5fz1ZPDCgk7EbII2jk2fDxtlMLoN5UYEJCcD8OUyivm3Hti3u1kPolckCCf0xk+80g/4EdmzFAffsVgPeXZrkm5EIuiTTOIeRHXlTg3HtkkCw2Wl0CpYSKBr9Vzv7x0gNvb1wnXPmBJNRgQIDAQAB", Privatekey = "MIIEpAIBAAKCAQEAyC43UbsE5XZ2Pmqg1YgzeCqAMk4HOH8fYHslseeSgKxyDjybjqM0yjGIJry1FRmVvLnY7v8jURgwr7d/pDCSRdoHa6zaxuSzg0OlieNmujae34YZ54PmFxULZW0BHSdzmx3OIYK2GarRECkds531ZzpbLdRXqsxQf5G26JZLIFxmNuh/VjBjJ6Hic1WOFT+FCYyi8om+LkPn3jELeA7LPLXzFqzzxx0vo4yiAePrsX5WucWxf+Y8rZoDhRIy/cPtQECXi9SiAWOJe/82JqjVjfpowf3QN7UJHsA82RBloAS4lvvDGJA7a+8DDlqpqPer8cS41Dv5r39iqtJUybDqoQIDAQABAoIBAHi39kBhiihe8hvd7bQX+QIEj17G02/sqZ1jZm4M+rqCRB31ytGP9qvghvzlXEanMTeo0/v8/O1Qqzusa1s2t19MhqEWkrDTBraoOtIWwsKVYeXmVwTY9A8Db+XwgHV2by8iIEbxLqP38S/Pu8uv/GgONyJCJcQohnsIAsfsqs2OGggz+PplZaXJfUkPomWkRdHM9ZWWDLrCIlmRSHLmhHEtFJaXD083kqo437qra58Amw/n+2gH57utbAQ9V3YQFjD8zW511prC+mB6N/WUlaLstkxswGJ16obEJfQ0r8wYHx14ep6UKGyi3YXlMHcteI8gz+uFx4RuVV9EotdXagECgYEA7AEz9oPFYlW1H15OkDGy8yBnpJwIBu2CQLxINsxhrLIAZ2Bgxqcsv+D9CpnYCBDisbXoGoyMK6XaSypBMRKe2y8yRv4c+w00rcKHtGfRjzSJ5NQO0Tv+q8vKY+cd6BuJ6OUQw82ICLANIfHJZNxtvtTCmmqBwSJDpcQJQXmKXTECgYEA2SQCSBWZZONkvhdJ15K+4IHP2HRbYWi+C1OvKzUiK5bdJm77zia4yJEJo5Y/sY3mV3OK0Bgb7IAaxL3i0oH+WNTwbNoGpMlYHKuj4x1453ITyjOwPNj6g27FG1YSIDzhB6ZC4dBlkehi/7gIlIiQt1wkIZ+ltOqgI5IqIdXoSHECgYB3zCiHYt4oC1+UW7e/hCrVNUbHDRkaAygSGkEB5/9QvU5tK0QUsrmJcPihj/RUK9YW5UK7b0qbwWWsr/dFpLEUi8GWvdkSKuLprQxbrDN44O96Q5Z96Vld9WV4DtJkhs4bdWNsMQFzf4I7D9PuKeJfcvqRjaztz6nNFFSqcrqkkQKBgQCJKlUCohpG/9notp9fvQQ0n+viyQXcj6TVVOSnf6X5MRC8MYmBHTbHA8+59bSAfanO/l7muwQQro+6TlUVMyaviLvjlwpxV/sACXC6jCiO06IqreIbXdlJ41RBw2op0Ss5gM5pBRLUS58V+HP7GBWKrnrofofXtAq6zZ8txok4EQKBgQCXrTeGMs7ECfehLz64qZtPkiQbNwupg938Z40Qru/G1GR9u0kmN7ibTyYauI6NNVHGEZa373EBEkacfN+kkkLQMs1tj5Zrlw+iITm+ad/irpXQZS/NHCcrg6h82vu0LcgiKnHKlmW6K5ne0w4LqmsmRCm7JdJjt9WlapAs0ticiw==" }; gateways.Add(new AlipayGateway(alipayMerchant) { GatewayUrl = "https://openapi.alipaydev.com" }); #endregion #region gateways.RegisterWechatpay(); //gateways.RegisterWechatpay(); var wechatpayMerchant = new PaySharp.Wechatpay.Merchant { AppId = "wx2428e34e0e7dc6ef", MchId = "1233410002", Key = "e10adc3849ba56abbe56e056f20f883e", AppSecret = "51c56b886b5be869567dd389b3e5d1d6", SslCertPath = AppDomain.CurrentDomain.BaseDirectory + "Certs/apiclient_cert.p12", SslCertPassword = "******", NotifyUrl = "http://localhost:64852/Notify" }; gateways.Add(new WechatpayGateway(wechatpayMerchant)); #endregion #region gateways.RegisterUnionpay(); //gateways.RegisterUnionpay(); var unionpayMerchant = new PaySharp.Unionpay.Merchant { AppId = "777290058110048", CertPwd = "000000", CertPath = AppDomain.CurrentDomain.BaseDirectory + "Certs/acp_test_sign.pfx", NotifyUrl = "http://localhost:50160/Notify", ReturnUrl = "http://localhost:50160/Notify" }; gateways.Add(new UnionpayGateway(unionpayMerchant) { GatewayUrl = "https://gateway.test.95516.com" }); #endregion return(gateways); }).As <IGateways>().InstancePerRequest(); // 第三步:注册系统容器,所有对象都从这里获取。 Container = builder.Build(); //5.0 将当前容器交给MVC底层,保证容器不被销毁,控制器由autofac来创建 GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container); GlobalHost.DependencyResolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(Container); //注册系统级别的 DependencyResolver,这样当 MVC 框架创建 Controller 等对象的时候都是管 Autofac 要对象。 DependencyResolver.SetResolver(new AutofacDependencyResolver(Container)); }
//Register Ninject Modules public static void RegisterModules(NinjectModule[] modules) { _resolver = new NinjectHttpResolver(modules); DependencyResolver.SetResolver(_resolver); }
public void Initialize(InitializationEngine context) { DependencyResolver.SetResolver(new ServiceLocatorDependencyResolver(context.Locate.Advanced)); }
public static void Initialise() { var container = BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); }
public void Execute() { DependencyResolver.SetResolver( this.dependencyResolver.Resolve, (t) => this.dependencyResolver.ResolveAll(t).Cast <object>()); }
public static void Configuration(IAppBuilder app) { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); var connectionString = ConfigurationManager.ConnectionStrings["MSSQL"]; if (connectionString == null) { throw new Exception("Не найдена строка соединения"); } var assembly = Assembly.GetAssembly(typeof(User)); var builder = new ContainerBuilder(); foreach (var type in assembly.GetTypes()) { var attr = (ListenerAttribute)type.GetCustomAttribute(typeof(ListenerAttribute)); if (attr != null) { var interfaces = type.GetInterfaces(); var b = builder.RegisterType(type); foreach (var inter in interfaces) { b = b.As(inter); } } } builder.Register(x => { var cfg = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2012 .ConnectionString(connectionString.ConnectionString) .Dialect <MsSql2012Dialect>()) .Mappings(m => m.FluentMappings.AddFromAssemblyOf <User>()) .ExposeConfiguration(c => { SchemaMetadataUpdater.QuoteTableAndColumns(c); c.EventListeners.PreInsertEventListeners = x.Resolve <IPreInsertEventListener[]>(); c.EventListeners.PreUpdateEventListeners = x.Resolve <IPreUpdateEventListener[]>(); }) .CurrentSessionContext("call"); var conf = cfg.BuildConfiguration(); var schemaExport = new SchemaUpdate(conf); schemaExport.Execute(true, true); return(cfg.BuildSessionFactory()); }).As <ISessionFactory>().SingleInstance(); builder.Register(x => x.Resolve <ISessionFactory>().OpenSession()) .As <ISession>() .InstancePerRequest(); builder.Register(x => x.Resolve <ISessionFactory>().OpenSession()) .As <ISession>() .InstancePerDependency(); builder.RegisterControllers(Assembly.GetAssembly(typeof(AccountController))); builder.RegisterModule(new AutofacWebTypesModule()); foreach (var type in assembly.GetTypes()) { var attr = type.GetCustomAttribute(typeof(RepositoryAttribute)); if (attr != null) { builder.RegisterType(type); } } var container = builder.Build(); Locator.SetImpl(new AutofacLocatorImpl(container)); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); app.UseAutofacMiddleware(container); app.CreatePerOwinContext(() => new UserManager(new IdentityStore(DependencyResolver.Current.GetServices <ISession>().FirstOrDefault()))); app.CreatePerOwinContext <SignInManager>((options, context) => new SignInManager(context.GetUserManager <UserManager>(), context.Authentication)); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider() }); }
/// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel)); GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel); }
/// <summary> /// Metoda OnApplicationStarted /// </summary> /// <param name="umbracoApplication">obiekt UmbracoApplicationBase</param> /// <param name="applicationContext">obiekt ApplicationContext</param> public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { RouteConfig.RegisterRoutes(RouteTable.Routes); FiltersConfig.RegisterFilters(GlobalFilters.Filters); GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; GlobalConfiguration.Configuration.Formatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = false; SetupAutoMapper(); SetupCustomTables(applicationContext); var config = GlobalConfiguration.Configuration; //Dependency injection autofac builder var builder = new ContainerBuilder(); //builder.RegisterInstance(ApplicationContext.Current).AsSelf(); builder.RegisterApiControllers(typeof(UmbracoApplication).Assembly); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(typeof(ArticleTypeDBTreeController).Assembly); //Rejestracja interfejsów builder.RegisterType <ConfigService>().As <IConfigService>(); builder.RegisterType <LayoutService>().As <ILayoutService>(); builder.RegisterType <HomeService>().As <IHomeService>(); builder.RegisterType <NewsService>().As <INewsService>(); builder.RegisterType <DBService>().As <IDBService>(); builder.RegisterType <UmbracoHelperService>().As <IUmbracoHelperService>(); builder.RegisterType <ISSApiService>().As <IISSApiService>(); builder.RegisterType <RegioApi>().As <IRegioApi>(); builder.RegisterType <ArticleService>().As <IArticleService>(); builder.RegisterType <CacheService>().As <ICacheService>(); builder.RegisterType <BoxListService>().As <IBoxListService>(); builder.RegisterType <AdvertisingOfSalesService>().As <IAdvertisingOfSalesService>(); builder.RegisterType <ContractNoticesService>().As <IContractNoticesService>(); builder.RegisterType <OffersService>().As <IOffersService>(); builder.RegisterType <AccordionService>().As <IAccordionService>(); builder.RegisterType <WiremapService>().As <IWiremapService>(); builder.RegisterType <SearchService>().As <ISearchService>(); builder.RegisterType <TicketOfficesService>().As <ITicketOfficesService>(); builder.RegisterType <BIPService>().As <IBIPService>(); builder.RegisterType <EmailService>().As <IEmailService>(); builder.RegisterType <DisabilitiesSupportService>().As <IDisabilitiesSupportService>(); builder.RegisterType <TagsService>().As <ITagsService>(); builder.RegisterType <AccountService>().As <IAccountService>(); builder.RegisterType <UserRepository>().As <IUserRepository>(); builder.RegisterType <MappingService>().As <IMappingService>(); builder.RegisterType <HashingService>().As <IHashingService>(); builder.RegisterType <SocialMediaService>().As <ISocialMediaService>(); builder.RegisterType <SalesManagoService>().As <ISalesManagoService>(); builder.RegisterType <SalesManagoRecommendedArticleService>().As <ISalesManagoRecommendedArticleService>(); builder.RegisterType <EPodroznikService>().As <IEPodroznikService>(); builder.RegisterType <KoleoService>().As <IKoleoService>(); builder.RegisterApiControllers(typeof(Umbraco.Forms.Web.Controllers.UmbracoFormsController).Assembly); //register event bus builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()) .Where(x => x.IsAssignableTo <IEventHandler>()) .AsImplementedInterfaces(); builder.Register <Func <Type, IEnumerable <IEventHandler> > >(c => { var ctx = c.Resolve <IComponentContext>(); return(t => { var handlersCollectionType = typeof(IEnumerable <>).MakeGenericType(t); return (IEnumerable <IEventHandler>)ctx.Resolve(handlersCollectionType); }); }); builder.RegisterType <EventBus>().As <IEventBus>(); var container = builder.Build(); var resolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = resolver; //setup the mvc dependency resolver to user autofac DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); RegisterUmbracoEvent(container.Resolve <IEventBus>()); }
public static void RegisterAutofac() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); //开启了Controller的依赖注入功能,这里使用Autofac提供的RegisterControllers扩展方法来对程序集中所有的Controller一次性的完成注册 builder.RegisterFilterProvider(); //开启了Filter的依赖注入功能,为过滤器使用属性注入必须在容器创建之前调用RegisterFilterProvider方法,并将其传到AutofacDependencyResolver #region IOC注册区域 //倘若需要默认注册所有的,请这样写(主要参数需要修改) //var baseType = typeof(IDependency); //var asssemblys = AppDomain.CurrentDomain.GetAssemblies().ToList(); //builder.RegisterControllers(asssemblys.ToArray()); //builder.RegisterAssemblyTypes(asssemblys.ToArray()) // .Where(t => baseType.IsAssignableFrom(t) && t != baseType) // .AsImplementedInterfaces().InstancePerMatchingLifetimeScope(); //注册一个接口多个实现并定义多个Name的情况需要使用的Helper类 builder.RegisterType <AutofacHelper>().As <IAutofacHelper>().InstancePerHttpRequest(); //Member builder.RegisterType <AccountService>().As <IAccountService>().InstancePerHttpRequest(); builder.RegisterType <ModuleService>().As <IModuleService>().InstancePerHttpRequest(); builder.RegisterType <RoleService>().As <IRoleService>().InstancePerHttpRequest(); builder.RegisterType <UserService>().As <IUserService>().InstancePerHttpRequest(); builder.RegisterType <UserGroupService>().As <IUserGroupService>().InstancePerHttpRequest(); builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerHttpRequest(); builder.RegisterType <EFDbContext>().As <DbContext>().InstancePerHttpRequest(); builder.RegisterType <EFUnitOfWork>().As <IUnitOfWork>().InstancePerHttpRequest(); builder.RegisterType <UserRepository>().As <IUserRepository>().InstancePerHttpRequest(); builder.RegisterType <UserGroupRepository>().As <IUserGroupRepository>().InstancePerHttpRequest(); builder.RegisterType <RoleRepository>().As <IRoleRepository>().InstancePerHttpRequest(); builder.RegisterType <PermissionRepository>().As <IPermissionRepository>().InstancePerHttpRequest(); builder.RegisterType <ModuleRepository>().As <IModuleRepository>().InstancePerHttpRequest(); //App services builder.RegisterType <RefundTypeService>().As <IRefundTypeService>().InstancePerHttpRequest(); builder.RegisterType <RefundTypeRepository>().As <IRefundTypeRepository>().InstancePerHttpRequest(); builder.RegisterType <BankService>().As <IBankService>().InstancePerHttpRequest(); builder.RegisterType <BankRepository>().As <IBankRepository>().InstancePerHttpRequest(); builder.RegisterType <BankFullNameService>().As <IBankFullNameService>().InstancePerHttpRequest(); builder.RegisterType <BankFullNameRepository>().As <IBankFullNameRepository>().InstancePerHttpRequest(); builder.RegisterType <SafeguardTimeService>().As <ISafeguardTimeService>().InstancePerHttpRequest(); builder.RegisterType <SafeguardTimeRepository>().As <ISafeguardTimeRepository>().InstancePerHttpRequest(); builder.RegisterType <DepartmentService>().As <IDepartmentService>().InstancePerHttpRequest(); builder.RegisterType <DepartmentRepository>().As <IDepartmentRepository>().InstancePerHttpRequest(); builder.RegisterType <TaskManageService>().As <ITaskManageService>().InstancePerHttpRequest(); builder.RegisterType <TaskManageRepository>().As <ITaskManageRepository>().InstancePerHttpRequest(); builder.RegisterType <TitleService>().As <ITitleService>().InstancePerHttpRequest(); builder.RegisterType <TitleRepository>().As <ITitleRepository>().InstancePerHttpRequest(); builder.RegisterType <AuditOpinionService>().As <IAuditOpinionService>().InstancePerHttpRequest(); builder.RegisterType <AuditOpinionRepository>().As <IAuditOpinionRepository>().InstancePerHttpRequest(); builder.RegisterType <ApplicationFormService>().As <IApplicationFormService>().InstancePerHttpRequest(); builder.RegisterType <ApplicationFormRepository>().As <IApplicationFormRepository>().InstancePerHttpRequest(); builder.RegisterType <TaxBaseByMonthService>().As <ITaxBaseByMonthService>().InstancePerHttpRequest(); builder.RegisterType <TaxBaseByMonthRepository>().As <ITaxBaseByMonthRepository>().InstancePerHttpRequest(); builder.RegisterType <PersonalRecordService>().As <IPersonalRecordService>().InstancePerHttpRequest(); builder.RegisterType <PersonalRecordRepository>().As <IPersonalRecordRepository>().InstancePerHttpRequest(); builder.RegisterType <TopContactsService>().As <ITopContactsService>().InstancePerHttpRequest(); builder.RegisterType <TopContactsRepository>().As <ITopContactsRepository>().InstancePerHttpRequest(); builder.RegisterType <TaxPerOrderService>().As <ITaxPerOrderService>().InstancePerHttpRequest(); builder.RegisterType <TaxPerOrderRepository>().As <ITaxPerOrderRepository>().InstancePerHttpRequest(); builder.RegisterType <TaxPerOrderHistoryService>().As <ITaxPerOrderHistoryService>().InstancePerHttpRequest(); builder.RegisterType <TaxPerOrderHistoryRepository>().As <ITaxPerOrderHistoryRepository>().InstancePerHttpRequest(); builder.RegisterType <StatisticsRepository>().As <IStatisticsRepository>().InstancePerHttpRequest(); builder.RegisterType <StatisticsService>().As <IStatisticsService>().InstancePerHttpRequest(); builder.RegisterType <TaxBaseEveryMonthService>().As <ITaxBaseEveryMonthService>().InstancePerHttpRequest(); builder.RegisterType <TaxBaseEveryMonthRepository>().As <ITaxBaseEveryMonthRepository>().InstancePerHttpRequest(); //Excel services builder.RegisterType <ApplyPrintService>().As <IApplyPrintService>().InstancePerHttpRequest(); #endregion // then var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
public static void Start() { var container = (IContainer)IoC.Initialize(); DependencyResolver.SetResolver(new SmDependencyResolver(container)); }