While not incorrect by any means, IoC/DI can be as simple as:
/*
* Simple Inversion of Control/Dependency Injection
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Configuration;
using USCG_SSO.Interfaces;
namespace USCG_SSO
{
public class ObjectFactory : IObjectFactory
{
public ObjectFactory() { }
// Create an instance of an object
public T getInstance()
{
return getInstance(null);
}
// Overload create instance of an object using creation parameters
public T getInstance(object\[\] initializationParameters)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
Type type = Activator.CreateInstance(typeof(T), initializationParameters).GetType();
// Any special initialization for an object should be placed in a case statement
// using that object's fully qualified type name
if (initializationParameters == null)
{
switch (type.ToString())
{
case "USCG\_SSO.ServiceUser":
NameValueCollection appSettings = ConfigurationManager.AppSettings;
initializationParameters = new object\[\]
{
appSettings\["ADUserID"\],
appSettings\["ADUserPassword"\],
appSettings\["ADFieldName"\]
}
break;
case "USCG\_SSO.ActiveDirectory"
initializationParameters = new object\[\]
{
new ObjectFactory().getInstance(),
new ObjectFactory().getInstance()
}
break;
default:
break;
}
}
return (T)Activator.CreateInstance(typeof(T), initializationParameters);
}
}
}
Assuming: USCG_SSO.ActiveDirectory object requires a ServiceUser object and a CurrentUser object to be passed in it's constructor, and USCG_SSO.ServiceUser object requires values retreived from the .config file in it's constructor. If you call
IActiveDirectory ADObject = new ObjectFactory().getInstance();
You would obtain an ActiveDirectory object complete with all of it's dependencies. Now, granted, this isn't as "fancy" or extensible as an actual IoC framework (there's no registration of dependencies, auto-resolution, etc.), it is, however, a complete, very simple IoC/DI implementation.
Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.R