/// <summary> /// resolves an instance of this type /// </summary> /// <param name="Container">Container holding the registerd object</param> /// <param name="RegisteredObjectToBuild">Registered Object To Get The Instance Of</param> /// <returns>The resolved instance</returns> public object ResolveInstance(ToracDIContainer Container, RegisteredUnTypedObject RegisteredObjectToBuild) { //**so expression tree is slower if you are just running resolve a handful of times. You would need to get into the 10,000 resolves before it starts getting faster. //**since an asp.net mvc site will handle request after request the pool won't get recycled before 10,000. So we are going to build it for scalability with expression trees //instead of using activator, we are going to use an expression tree which is a ton faster. //so we are going to build a func that takes a params object[] and then we just set it to each item. //if we haven't already built the expression, then let's build and compile it now //singleton will only create it once, so singleton's will use the regular activator because it won't benefit of creating the object once. The cost //of the expression tree compile is too hight. //do we need to create an instance? This handles the derived per thread scoped object if (Instance != null) { //we have a valid instance, return it return Instance; } //go build the instance and store it Instance = Activator.CreateInstance(RegisteredObjectToBuild.ConcreteType, RegisteredObjectToBuild.ResolveConstructorParametersLazy(Container).ToArray()); //now return the object we created. Don't return the instance which could be a derived typed return Instance; }
/// <summary> /// Constructor /// </summary> /// <param name="FactoryNameToSet"> Unique Identifier when you have the same types to resolve. Abstract Factory Pattern usages</param> /// <param name="TypeToResolveToSet"> Type to resolve. ie: ILogger</param> /// <param name="ConcreteTypeToSet">Implementation of the Type to resolve. ie: TextLogger</param> /// <param name="ObjectScopeToSet">How long does does the object last in the di container</param> public AllRegistrationResult(string FactoryNameToSet, ToracDIContainer.DIContainerScope ObjectScopeToSet, Type TypeToResolveToSet, Type ConcreteTypeToSet) { //set all the properties FactoryName = FactoryNameToSet; TypeToResolve = TypeToResolveToSet; ConcreteType = ConcreteTypeToSet; ObjectScope = ObjectScopeToSet; }
/// <summary> /// Constructor to init the container /// </summary> static DIUnitTestContainer() { //create the new di container DIContainer = new ToracDIContainer(); //go configure the di container ConfigureDIContainer(DIContainer); }
/// <summary> /// resolves an instance of this type /// </summary> /// <param name="Container">Container holding the registerd object</param> /// <param name="RegisteredObjectToBuild">Registered Object To Get The Instance Of</param> /// <returns>The resolved instance</returns> public object ResolveInstance(ToracDIContainer Container, RegisteredUnTypedObject RegisteredObjectToBuild) { //if we have a valid object and its still alive then return it if (Instance == null || !Instance.IsAlive) { //at this point we don't have a valid object, we need to create it and put it in the property Instance = new WeakReference(CachedActivator.Invoke(RegisteredObjectToBuild.ResolveConstructorParametersLazy(Container).ToArray())); } //now just return the instance's target. return Instance.Target; }
public static ControllerExtensionTestController MockController(ToracDIContainer DIContainer) { //create the controller var MockedController = new ControllerExtensionTestController(); //create the Mock controller MockedController.ControllerContext = new MockControllerContext(MockedController, DIContainer.Resolve<MockPrincipal>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockIdentity>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockHttpRequest>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockHttpResponse>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockHttpSessionState>(AspNetDIContainerSharedMock.AspNetMockFactoryName)); //return the controller now return MockedController; }
/// <summary> /// Constructor /// </summary> /// <param name="ObjectScopeToSet">Scope of the object to use</param> /// <param name="TypeToResolveToSet">Type to resolve. Usually an interface</param> /// <param name="ConcreteTypeToSet">Concrete type to create. Usually a class that implements TTypeToResolveToSet.</param> public RegisteredUnTypedObject(ToracDIContainer.DIContainerScope ObjectScopeToSet, Type TypeToResolveToSet, Type ConcreteTypeToSet) { //set the immutable properties TypeToResolve = TypeToResolveToSet; ConcreteType = ConcreteTypeToSet; ObjectScope = ObjectScopeToSet; //grab the constructor info var ConstructorInfoToUse = ConcreteType.GetConstructors().First(); //grab the constructor parameters and store them ConcreteConstructorParameters = ConstructorInfoToUse.GetParameters(); //depending on which scope to use, create the implementation ScopeImplementation = CreateScopeImplementation(ObjectScope, ConstructorInfoToUse); }
public static JsonNetCustomValueProviderFactoryControllerTest MockController(ToracDIContainer DIContainer) { //create the controller var MockedController = new JsonNetCustomValueProviderFactoryControllerTest(); //create the Mock controller MockedController.ControllerContext = new MockControllerContext(MockedController, DIContainer.Resolve<MockPrincipal>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockIdentity>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockHttpRequest>(JsonNetCustomValueProviderFactoryName), DIContainer.Resolve<MockHttpResponse>(AspNetDIContainerSharedMock.AspNetMockFactoryName), DIContainer.Resolve<MockHttpSessionState>(AspNetDIContainerSharedMock.AspNetMockFactoryName)); //return the controller now return MockedController; }
/// <summary> /// resolves an instance of this type /// </summary> /// <param name="Container">Container holding the registerd object</param> /// <param name="RegisteredObjectToBuild">Registered Object To Get The Instance Of</param> /// <returns>The resolved instance</returns> public object ResolveInstance(ToracDIContainer Container, RegisteredUnTypedObject RegisteredObjectToBuild) { //use the activator and go create the instance //return Activator.CreateInstance(RegisteredObjectToBuild.ConcreteType, ConstructorParameters); //**so expression tree is slower if you are just running resolve a handful of times. You would need to get into the 10,000 resolves before it starts getting faster. //**since an asp.net mvc site will handle request after request the pool won't get recycled before 10,000. So we are going to build it for scalability with expression trees //instead of using activator, we are going to use an expression tree which is a ton faster. //so we are going to build a func that takes a params object[] and then we just set it to each item. //if we haven't already built the expression, then let's build and compile it now //transients will benefit from the expression tree. singleton will only create it once, so singleton's will use the regular activator //we have the expression, so let's go invoke it and return the results return CachedActivator.Invoke(RegisteredObjectToBuild.ResolveConstructorParametersLazy(Container).ToArray()); }
public static MockHttpRequest MockRequest(ToracDIContainer DIContainer) { //let's build a model with a stream var MemoryStreamToUse = new MemoryStream(); //stream writer var StreamWriterToUse = new StreamWriter(MemoryStreamToUse); //write the string value StreamWriterToUse.Write(JsonNetSerializer.Serialize(AjaxPostModel.BuildModel())); //flush the data StreamWriterToUse.Flush(); //reset the stream MemoryStreamToUse.Position = 0; //go build hte request and return it return new MockHttpRequest(null, null, null, null, AspNetConstants.JsonContentType, MemoryStreamToUse); }
public void AspMvcWorksWithDIContainerTest1() { //first thing we need to do is declare the container var DIContainer = new ToracDIContainer(); //let's go configure the bootstrapper ToracDIBootstrapper.Configure(DIContainer); //let's go create the default controller factory var MockedDefaultControllerFactory = new ToracDIDefaultControllerFactory(DIContainer); //let's go grab mock the request context var ControllerToUse = (HomeControllerDIContainerTest)MockedDefaultControllerFactory.GetControllerInstanceMock(new RequestContext(), typeof(HomeControllerDIContainerTest)); //description to log const string DescriptionToLog = "Test123"; //now go check that value Assert.Equal(DescriptionToLog, ControllerToUse.Logger.WriteToLog(DescriptionToLog)); }
/// <summary> /// Gets the parameter value for the given constructor parameter implementation /// </summary> /// <param name="Container">Current container to fetch the parameter from</param> /// <returns>The parameter value</returns> public object GetParameterValue(ToracDIContainer Container) { //just invoke the expression and return it return ResolveExpression(Container); }
/// <summary> /// Gets the parameter value for the given constructor parameter implementation /// </summary> /// <param name="Container">The container which we are currently using to resolve items</param> /// <returns>The parameter value</returns> public object GetParameterValue(ToracDIContainer Container) { //just return whatever we have saved return Container.Resolve(TypeToResolve); }
/// <summary> /// Builds and returns the concrete implementation of the IScopeImplementation. /// </summary> /// <param name="Scope">Scope of the object to use</param> /// <param name="ConstructorToUse">Constructor to use to create the concrete type</param> /// <returns>new IScopeImplementation implementation</returns> internal IScopeImplementation CreateScopeImplementation(ToracDIContainer.DIContainerScope Scope, ConstructorInfo ConstructorToUse) { //which scope is it? //this is probably the most used, so we will put it first if (Scope == ToracDIContainer.DIContainerScope.Transient) { return new TransientScopedObject(ConstructorToUse); } if (Scope == ToracDIContainer.DIContainerScope.Singleton) { return new SingletonScopedObject(); } return new PerThreadScopedObject(ConstructorToUse); }
/// <summary> /// Get the constructor parameters to pass into the constructor /// </summary> /// <param name="DIContainer">Container to build off of</param> /// <returns>Parameters to pass into the constructor</returns> internal IEnumerable<object> ResolveConstructorParametersLazy(ToracDIContainer DIContainer) { //loop through the parameters and yield it (i don't want an interator inside interator so ResolveWhichConstructorParametersToImplement will not be lazy foreach (var ConstructorParameter in ResolveWhichConstructorParametersToImplement()) { //return this value yield return ConstructorParameter.GetParameterValue(DIContainer); } }
/// <summary> /// Gets the parameter value for the given constructor parameter implementation /// </summary> /// <param name="Container">The container which we are currently using to resolve items</param> /// <returns>The parameter value</returns> public object GetParameterValue(ToracDIContainer Container) { //just return whatever we have saved return ParameterValue; }
public ToracDIDefaultControllerFactory(ToracDIContainer ContainerToSet) { this.Container = ContainerToSet; }
public static void Configure(ToracDIContainer ContainerToConfigure) { ContainerToConfigure.Register<HomeControllerDIContainerTest>(); ContainerToConfigure.Register<StringLogger>(); }
private static void ConfigureDIContainer(ToracDIContainer Container) { //start of entity framework configuration Container.Register<EntityFrameworkDP<EntityFrameworkEntityDP>>() .WithFactoryName(EntityFrameworkTest.ReadonlyDataProviderName) .WithConstructorImplementation((di) => new EntityFrameworkDP<EntityFrameworkEntityDP>(false, true, false)); Container.Register<EntityFrameworkDP<EntityFrameworkEntityDP>>() .WithFactoryName(EntityFrameworkTest.WritableDataProviderName) .WithConstructorImplementation((di) => new EntityFrameworkDP<EntityFrameworkEntityDP>(true, true, false)); //end of entity framework configuration //************************************************************ //start of sql data provider configuration DIContainer.Register<IDataProvider, SQLDataProvider>() .WithConstructorParameters(new PrimitiveCtorParameter(SqlDataProviderTest.ConnectionStringToUse())); //end of sql data provider configuration //************************************************************ //asp net shared mock start //now let's register a simple mock http response DIContainer.Register<MockHttpResponse>() .WithFactoryName(AspNetDIContainerSharedMock.AspNetMockFactoryName); //add a mocked request (simple mock request) DIContainer.Register<MockHttpRequest>() .WithFactoryName(AspNetDIContainerSharedMock.AspNetMockFactoryName) .WithConstructorImplementation((di) => new MockHttpRequest(null, null, null, null, null, null)); //add a mocked session state DIContainer.Register<MockHttpSessionState>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(AspNetDIContainerSharedMock.AspNetMockFactoryName) .WithConstructorImplementation((di) => new MockHttpSessionState(null)); //add the identity DIContainer.Register<MockIdentity>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(AspNetDIContainerSharedMock.AspNetMockFactoryName) .WithConstructorParameters(new PrimitiveCtorParameter("TestUser")); //add the mocked principal DIContainer.Register<MockPrincipal>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(AspNetDIContainerSharedMock.AspNetMockFactoryName) .WithConstructorImplementation((di) => new MockPrincipal(di.Resolve<MockIdentity>(), new string[] { "Role1", "Role2" })); //end of asp net shared mock. //************************************************************ //start of html helper tests DIContainer.Register<ViewContext>() .WithFactoryName(HtmlHelperTest.HtmlHelperTestDIFactoryName) .WithConstructorOverload(); //register the IViewDataContainer DIContainer.Register<IViewDataContainer, MockIViewDataContainer>() .WithFactoryName(HtmlHelperTest.HtmlHelperTestDIFactoryName) .WithConstructorOverload(); //now let's register the actual html helper we are going to mock DIContainer.Register<HtmlHelper<HtmlHelperTest.HtmlHelperTestViewModel>>() .WithFactoryName(HtmlHelperTest.HtmlHelperTestDIFactoryName); //end of html helper tests //************************************************************ //start of json action result DIContainer.Register<JsonActionResultTest.JsonNetActionControllerTest>() .WithFactoryName(JsonActionResultTest.JsonActionResultFactoryName) .WithConstructorImplementation((di) => JsonActionResultTest.JsonNetActionControllerTest.MockController(di)); //end of json action result //************************************************************ //start of json net custom value factory DIContainer.Register<JsonNetCustomValueProviderFactoryControllerTest>() .WithFactoryName(JsonNetCustomValueProviderFactoryName) .WithConstructorImplementation((di) => JsonNetCustomValueProviderFactoryControllerTest.MockController(di)); //register the mocked request DIContainer.Register<MockHttpRequest>() .WithFactoryName(JsonNetCustomValueProviderFactoryName) .WithConstructorImplementation((di) => JsonNetCustomValueProviderFactoryControllerTest.MockRequest(di)); //end of json net custom value factory //************************************************************ //start of asp net test DIContainer.Register<MockHttpRequest>() .WithFactoryName(AspNetTest.MockFactoryNameForSessionStateExportWithBaseHttpRequest) .WithConstructorImplementation((di) => new MockHttpRequest(null, null, null, new HttpCookieCollection() { new HttpCookie(ExportCurrentSessionState.SessionStateCookieName, AspNetTest.SessionIdToTest) }, null, null)); //end of asp net test //************************************************************ //start of in memory cache //let's register my dummy cache container DIContainer.Register<ICacheImplementation<IEnumerable<DummyObject>>, InMemoryCache<IEnumerable<DummyObject>>>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(InMemoryCacheTest.DIFactoryName) .WithConstructorImplementation((di) => new InMemoryCache<IEnumerable<DummyObject>>(InMemoryCacheTest.CacheKeyToUse, () => InMemoryCacheTest.DummyObjectCacheNoDI.BuildCacheDataSource())); //end of in memory cache //************************************************************ //start of sql cache dep //let's register my dummy cache container DIContainer.Register<ICacheImplementation<IEnumerable<DummyObject>>, SqlCacheDependency<IEnumerable<DummyObject>>>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(SqlCacheDependencyTest.DIFactoryName) .WithConstructorImplementation((di) => new SqlCacheDependency<IEnumerable<DummyObject>>( SqlCacheDependencyTest.CacheKeyToUse, () => SqlCacheDependencyTest.DummySqlCacheObjectCacheNoDI.BuildCacheDataSource(), SqlDataProviderTest.ConnectionStringToUse(), SqlCacheDependencyTest.DatabaseSchemaUsedForCacheRefresh, SqlCacheDependencyTest.CacheSqlToUseToTriggerRefresh)); //end of sql cache dep //************************************************************ //start of email mock DIContainer.Register<ISMTPEmailServer, EmailTest.MockSMTPEmailServer>(); //end of email mock //************************************************************ //start of html parsing DIContainer.Register<HtmlParserWrapper>() .WithFactoryName(HtmlParsingTest.HtmlParserFactoryName) .WithConstructorImplementation((di) => new HtmlParserWrapper(string.Format($"<html><span class='{HtmlParsingTest.ClassNameInSpan}'>{HtmlParsingTest.SpanInnerTextValue}</span></html>"))); //end of html parsing //************************************************************ //start of encryption //let's register the di container now (md5) DIContainer.Register<ITwoWaySecurityEncryption, MD5HashSecurityEncryption>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(EncryptionSecurityTest.MD5DIContainerName) .WithConstructorParameters(new PrimitiveCtorParameter("Test")); //let's register the rijndael container now DIContainer.Register<ITwoWaySecurityEncryption, RijndaelSecurityEncryption>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(EncryptionSecurityTest.RijndaelDIContainerName) .WithConstructorParameters(new PrimitiveCtorParameter("1234567891123456"), new PrimitiveCtorParameter("1234567891123456")); //let's register the 1 way data binding DIContainer.Register<IOneWaySecurityEncryption, SHA256SecurityEncryption>(ToracDIContainer.DIContainerScope.Singleton) .WithFactoryName(EncryptionSecurityTest.SHA256ContainerName); //end of encryption //************************************************************ //start of controller extensions tests DIContainer.Register<ControllerExtensionTestController>() .WithFactoryName(ControllerExtensionFactoryName) .WithConstructorImplementation((di) => ControllerExtensionTestController.MockController(di)); //add the mock view engine DIContainer.Register<IViewEngine, MockIViewEngine>() .WithFactoryName(ControllerExtensionFactoryName) .WithConstructorImplementation((di) => new MockIViewEngine(new Dictionary<string, IView>() { { "_TestView", new CustomView() } })); //we will need to mock a view engine ViewEngines.Engines.Clear(); //now add the new mock view engine ViewEngines.Engines.Add(DIContainer.Resolve<IViewEngine>(ControllerExtensionFactoryName)); //end of controller extension tests }