In some scenarios I would like to override the values from the config file depending on the organization I'm processing the data for, in example I would like to increase the quota for some organization. Of course, I could create the method similar to:

public int GetQuotaByOrgId(int orgId);

and implement the logic there, but I would like to avoid passing the orgId among the code. The better solution for me would be to create a proxy class overriding only the values I want to change, something like:

public class OverridenSettings : ISettings

{

private ISettings instance;

private int orgId;

private int[] orgsWithBiggerQuota = {1, 2, 132, 6542};

public OverridenSettings(ISettings instance, int orgId)

{

this.instance = instance;

this.orgId = orgId;

}

public override int Quota

{

get

{

int quota = this.instance.Quota;

if (this.orgsWithBiggerQuota.Contains(this.orgId))

{

quota += 1000;

}

return quota;

}

}

// all other properties should be taken from the default instance

}

Is there an elegant way to generate such class without having to explicitely implement all the interface's members just to redirect them to the default instance?

网友答案:

You can use any of the frameworks out there to create a dynamic proxy of your Settings class.
For example using Unity I can create an object of a class(in your case Settings class) like this

I haven't ran this myself so you might need to debug it a bit(especially the Invoke method).

If you want to use the VirtualMethodInterceptor you need to declare your property virtual. There is also TransparentProxyInterceptor which doesnt require this but will create another object that will call into your object(2 objects in total vs 1 in the virtual case).