views:

31

answers:

1

We have a .Net object that has a static delegate (a data access strategy) that has to be set before the object can be instantiated. The delegate can also be passed in through one of the constructor overloads.

I have another object that has the delegate that I need to set, but I can't figure out in PowerShell how to do so. Does anyone know how to set a static delegate property or pass a delegate into a constructor in PowerShell?

I want to do something similar to this:

[DALObject]$db = New-Object DALObject;
[UnitOfWork]::Strategy = $db::CreateContext;

or

[DALObject]$db = New-Object DALObject;
[UnitOfWork]$uow = New-Object UnitOfWork($db::CreateConext);

Just for reference I am trying to reproduce the comparable C# code:

DalObject db = new DALObject();
UnitOfWork.Strategy = db.CreateContext;

or

UnitOfWork uow = new UnitOfWork(db.CreateContext);

Edit: To clarify Strategy is a static delegate

Public static Func<DataContext> Strategy 

and CreateContext is an instance method that I want to set to that delegate, either by setting the static Property or by passing in the method to the constructor.

Another option would be if there is there a way in PowerShell to create an anonymous delegate like this in C#:

 UnitOfWork.Strategy = delegate()
            {
                var ctx = db.CreateContext();
                return ctx;
            };
A: 

You can't access static members via an instance object (assuming here that CreateContext is a static property although it is named like a method). Try this:

[DALObject]$db = New-Object DALObject; 
[UnitOfWork]::Strategy = [DALObject]::CreateContext

or if it is a method

[DALObject]$db = New-Object DALObject; 
[UnitOfWork]::Strategy = [DALObject]::CreateContext()

OTOH if CreateContext is an instance member then change the [DALObject]::CreateContext to $db.CreateContext with or without parens depending on whether it is a method or not.

Update: In the case of assigning a scriptblock to a generic delegate, there is no built-in way to make this work AFAIK. Check out this blog post for a potential work-around.

Keith Hill