views:

71

answers:

1

Hi

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)

+2  A: 

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.

Maurice
Thanks for the answer. Are there any examples/tutorials available?
Fabiano
Added a sample.
Maurice
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?
Fabiano
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.
Maurice
ok, I got it :-) I also found this with information about iis hosted workflows http://social.msdn.microsoft.com/forums/en-us/wfprerelease/thread/A9B45EAF-C8E2-444C-819D-E448868E68BB (not tested)
Fabiano