Entering a value at run time

I have repository classes that require runtime values ​​taken from Thread.CurrentPrincipal

(i.e. authorization assertions) combined with regular singleton classes.

Considering

public class MyRepository : IMyRepository
{
    private readonly DependencyClass _dependency;
    private readonly string claim;

    protected MyRepository(DependencyClass _dependency, string claim)
    {
        //...

      

When registering a repository, how can I apply? eg.

unity.RegisterType<IMyRepository, MyRepository>(new HierarchicalLifetimeManager());
unity.RegisterType<DependencyClass>(new ContainerControlledLifetimeManager());

      

InjectionConstructor

seems to match the parameters of the constructor and therefore throws a runtime error. However, I would prefer the injection constructor, I'm just not sure how to do this.

+3


source to share


1 answer


I have repository classes that require runtime values

Your DI container should create an object graph containing injections / components; classes that contain the logic of your application. Run-time data should not be entered into the component designer, as this will make it difficult to plot, plot, and validate object plots.

Instead, runtime data must be passed through the object graph using method calls. The general solution for this kind of runtime contextual data is an abstraction that exposes this contextual data to its consumers.

In your case, for example, the abstraction IClaimsContext

does the trick:

public interface IClaimsContext {
    string CurrentClaim { get; }
}

      



Using this abstraction, it is trivial to create an implementation that reads formulas from Thread.CurrentPrincipal

, as you can here:

public sealed class ThreadClaimsContext : IClaimsContext {
    public string CurrentClaim {
        get { return Thread.CurrentPrincipal... /* get claims here */; }
    }
}

      

Since this implementation is stateless, it can be registered as a single one without problems:

unity.RegisterInstance<IClaimsContext>(new ThreadClaimsContext());

      

Now yours MyRepository

can just depend on IClaimsContext

instead string claims

.

+4


source







All Articles