Pergunta

I have an extension method where I want to be able to get an instance of a class via the container e.g.

public static string EncryptString(this SecureString input)
{
    if (input == null) return null;

    var encryptor = Injector.Container.GetInstance<ICryptFactory>().GetEncryptor(salt);

    return encryptor.Encrypt(input.ToInsecureString());
}

However, I don't really want the dependency on the container but I can't work out how else to get an instance.

Any ideas on how to do this?

Foi útil?

Solução

Ideally, you want to use constructor injection to inject the dependencies a class needs. An extension method however, is just a static method on a static class and you can't do constructor injection on static classes.

Because of this you are currently falling back to the Service Locator pattern, which is far from ideal and should be avoided whenever possible.

So you will either have to promote your class to a non-static class and your extension method to a non-static method to allow it to be injected as usual, or you will have to pass in the encryptor into the method.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top