Dependency injection / IoC in Workflow Foundation 4
Asked Answered
H

1

13

Is it possible to use DI in your workflow activities? and if yes, how?

For example if you have an activity like

public sealed class MyActivity : CodeActivity
{
    public MyClass Dependency { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        Dependency.DoSomething();
    }
}

how can i set Dependency?

(I'm using Spring.Net)

Hescock answered 29/9, 2010 at 20:57 Comment(2)
FYI, I have created some custom activities in my toolkit project that provide this functionality. I have termed it dependency resolution (Service Locator as Maurice as indicated). It will take care of activity persistence scenarios and cleanup any dependencies when they are finished with. neovolve.com/post/2010/10/01/…Rhetic
You can also add a simple DI container yourself as an extension and make it easily accessible from your Execute method's context. blog.petegoo.com/index.php/2010/08/16/…Trig
O
20

Workflow doesn't use an IOC container. It uses the ServiceLocator pattern where you add dependencies to the workflow runtime as extensions and workflow activities and retrieve these services from the workflow extensions through the context.

A ServiceLocator and IOC pattern are similar and have the same purpose in decoupling dependencies. The apporach is different though in an IOC container pushing dependencies in while a ServiceLocator is used to pull dependencies out.

Example activity:

public class MyBookmarkedActivity : NativeActivity
{
    protected override void CacheMetadata(NativeActivityMetadata metadata)
    {
        base.CacheMetadata(metadata);
        metadata.AddDefaultExtensionProvider<MyExtension>(() => new MyExtension());
    }

    protected override void Execute(NativeActivityContext context)
    {
        var extension = context.GetExtension<MyExtension>();
        extension.DoSomething();

    }
}

The MyExtension class is the extension here and it has no base class or interface requirements.

Overcast answered 30/9, 2010 at 6:34 Comment(4)
Thanks for the answer. Are there any examples/tutorials available?Hescock
Thanks again. But like this I have to add the extension within an activity. In our case the activities don't have the know how of construct the extension. Where can I add the extension when the workflow instance is constructed by the framework?Hescock
You can also add extensions to the WorkflowInvoker, WorkflowApplication or WorkflowServiceHost. Use the Extensions collection with the first 2 and the WorkflowExtensions with the WorkflowServiceHost.Overcast
ok, I got it :-) I also found this with information about iis hosted workflows social.msdn.microsoft.com/forums/en-us/wfprerelease/thread/… (not tested)Hescock

© 2022 - 2024 — McMap. All rights reserved.