আমি সবসময় যে কোনও আইওসি কনটেইনারটির জন্য অ্যাডাপ্টারের মোড়ক লিখি, যা দেখতে এটির মতো দেখাচ্ছে:
public static class Ioc
{
public static IIocContainer Container { get; set; }
}
public interface IIocContainer
{
object Get(Type type);
T Get<T>();
T Get<T>(string name, string value);
void Inject(object item);
T TryGet<T>();
}
নিিনজেক্টের জন্য, বিশেষত, কংক্রিট অ্যাডাপ্টার শ্রেণিটি দেখতে এরকম দেখাচ্ছে:
public class NinjectIocContainer : IIocContainer
{
public readonly IKernel Kernel;
public NinjectIocContainer(params INinjectModule[] modules)
{
Kernel = new StandardKernel(modules);
new AutoWirePropertyHeuristic(Kernel);
}
private NinjectIocContainer()
{
Kernel = new StandardKernel();
Kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
new AutoWirePropertyHeuristic(Kernel);
}
public object Get(Type type)
{
try
{
return Kernel.Get(type);
}
catch (ActivationException exception)
{
throw new TypeNotResolvedException(exception);
}
}
public T TryGet<T>()
{
return Kernel.TryGet<T>();
}
public T Get<T>()
{
try
{
return Kernel.Get<T>();
}
catch (ActivationException exception)
{
throw new TypeNotResolvedException(exception);
}
}
public T Get<T>(string name, string value)
{
var result = Kernel.TryGet<T>(metadata => metadata.Has(name) &&
(string.Equals(metadata.Get<string>(name), value,
StringComparison.InvariantCultureIgnoreCase)));
if (Equals(result, default(T))) throw new TypeNotResolvedException(null);
return result;
}
public void Inject(object item)
{
Kernel.Inject(item);
}
}
এটি করার প্রাথমিক কারণটি হ'ল আইওসি কাঠামোটি বিমূর্ত করা, সুতরাং আমি যে কোনও সময় এটি প্রতিস্থাপন করতে পারি - প্রদত্ত যে ফ্রেমওয়ার্কগুলির মধ্যে পার্থক্যটি সাধারণত ব্যবহারের চেয়ে কনফিগারেশনে থাকে।
তবে, বোনাস হিসাবে, অন্যান্য ফ্রেমওয়ার্কগুলির মধ্যে আইওসি ফ্রেমওয়ার্ক ব্যবহার করার জন্য জিনিসগুলি অনেক সহজ হয়ে যায় যা এটিকে সহজাতভাবে সমর্থন করে না। উইনফরমের জন্য, উদাহরণস্বরূপ, এটি দুটি ধাপ:
আপনার মূল পদ্ধতিতে, অন্য কিছু করার আগে কেবল একটি ধারক ইনস্ট্যান্ট করুন।
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Ioc.Container = new NinjectIocContainer( /* include modules here */ );
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyStartupForm());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
এবং তারপরে একটি বেস ফর্ম রয়েছে, যা থেকে অন্যান্য ফর্মগুলি আসে, যা নিজেই ইনজেকশনকে কল করে।
public IocForm : Form
{
public IocForm() : base()
{
Ioc.Container.Inject(this);
}
}
এটি অটো-ওয়্যারিং হিউরিস্টিককে বলে যে ফর্মের সমস্ত বৈশিষ্ট্যগুলি পুনরাবৃত্তভাবে ইনজেক্ট করার চেষ্টা করতে যা আপনার মডিউলগুলিতে সেট করা নিয়মগুলির সাথে খাপ খায়।