Manually implementing IoC with a Windows Service

会有一股神秘感。 提交于 2019-12-05 07:55:19

Based on the tags of this question (c#) I'm assuming that you'll implement the Windows Service by deriving from ServiceBase. If so, the OnStart method will be your Composition Root - this is where you compose the application's object graph. After you've composed the object graph, composition is over and the composed object graph takes over.

In OnStop you can decommission the object graph again.

There's nothing stopping you from implementing the various components of the resolved object graph in separate assemblies. That's what I would do.

I think you missunderstood the role of an IoC framework.

To answer your question

but doesn't the reference imply dependency?

Yes it does, but on an other level. IoC is about dependencies between classes. Instead of using new Something() in your class you provide a constructor which requires all dependent interfaces. This way the class has no control which implementation is passed to it. This is inversion of control. The IoC Container is just an aid to help managing the dependencies in a nice manner.

Say you have a ICustomerNotificationService interface with an implementation like

public class MailNotificationService : INotificationService
{
    IMailerService _mailer;
    ICustomerRepository _customerRepo;
    IOrderRepository _orderRepo;

    public MailNotificationService(IMailerService mailer, 
                                   ICustomerRepository customerRepo, 
                                   IOrderRepository oderRepo)
    {
        // set fields...
    }

    public void Notify(int customerId, int productId)
    {
        // load customer and order, format mail and send.
    }
}

So if your application requests an instance of ICustomerNotificationServcie the container figures out which concrete implementations to take and tries to satisfy all dependencies the requested class has.

The advantage is that you can easily configure all dependencies in your bootstrapping logic and be able to change the behaviour of your application very easily.

For example when testing you start the application with an IMailerService implementation which writes the mails to a file and in production mode a real mail service is wired. This would not be possible if you newed up say a MailerService in your constructor instead of taking it as a parameter.

A good IoC container can handle much more, for you like lifetime management, singletons, scanning assemblies for Types you want to register and many more. We based our entire plugin system on Structure Map for example.

You may want to take a look at this blog article and its second part.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!