I'm writing an app that makes use of classes defined by the following interface:
public interface ICredentialProvider
{
string GetUsername();
string GetPassword();
}
This is done so methods can be called to retrieve the username/password instead of it being statically held in memory and defined in code/config file.
Currently in development I'm using this very simple implementation:
public class FakedCredentialProvider : ICredentialProvider
{
private readonly string _username;
private readonly string _password;
public FakedCredentialProvider(string username, string password)
{
_username = username;
_password = password;
}
public string GetUsername()
{
return _username;
}
public string GetPassword()
{
return _password;
}
}
...which accepts two strings in the constructor. Future (actual) implementations of ICredentialProvider
will likely need to accept certain strings for connecting to the appropriate external password vault or service (or possibly both; at this point in the project that's unclear).
Further, the project uses multiple instances of ICredentialProvider
for the various accounts it needs to connect to (such as SharePoint, ActiveDirectory, and Windows Graph).
To these ends I know how to register via a delegate:
container.RegisterWebApiRequest(() =>
new FakedCredentialProvider(fakedSharePointUsername, fakedSharePointPassword));
...And how to conditionally register...
container.RegisterConditional(typeof(ICredentialProvider), typeof(FakedCredentialProvider),
context =>
context.Consumer.Target.Name.ToLower().Contains("sharepoint")
);
...But not how to combine the two.
How does one combine these two approaches? Or alternatively: Is there an better design for situations such as these?
I'm not sure whether I fully understand your constraints and design, but the way to do registration of conditional delegates is using one of the RegisterConditional
overloads that accepts a Registration
object:
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
container.RegisterConditional(typeof(ICredentialProvider),
Lifestyle.Scoped.CreateRegistration(() => new FakedCredentialProvider(user, pwd),
container),
c => c.Consumer.Target.Name.ToLower().Contains("sharepoint"));