YairHalberstadt / stronginject

compile time dependency injection for .NET
MIT License
845 stars 24 forks source link

'registerAs' parameter for FactoryAttribute #151

Closed jnm2 closed 2 years ago

jnm2 commented 2 years ago

When converting existing apps, I found a situation where a concrete type is registered as two different interface types that it implements, and a factory is required in order to create it.

I'd like to be able to do this, consistent with how the Register attribute is used:

[Factory(Scope.SingleInstance, typeof(IAppSettingsProvider<FooAppSettings>), typeof(IAppSettingsProvider<ICommonAuthenticationSettings>))]
private static AppSettingsProvider<FooAppSettings> CreateAppSettingsProvider(IBar bar)
{
    // ...
}

I wasn't able to find a workaround where StrongInject would use the same instance for both interface types and where IBar would be available to aid in part of the AppSettingsProvider<FooAppSettings> creation.

YairHalberstadt commented 2 years ago

You could probably do a workaround using the FactoryOfAttribute, but this seems reasonable and something I would like to support.

jnm2 commented 2 years ago

@YairHalberstadt FactoryOfAttribute seemed to require the method to be generic or it gave me a compile error. Maybe I didn't try it the right way?

YairHalberstadt commented 2 years ago

It does but you could have a Factory and a Generic method which forwarded the result of that factory.

jnm2 commented 2 years ago

I'll try to get this done now that I have a PR up for something else.

YairHalberstadt commented 2 years ago

I'm working on this at the moment, but slowly. So it will probably get done if you wait, or I can push what under done so far, and you can carry on from there.

jnm2 commented 2 years ago

Ah, okay. If it's already in progress then I can wait. I could give it a shot but that might be less efficient overall?

YairHalberstadt commented 2 years ago

I can't speak to less efficient or not. I haven't been able to put a huge amount of time into it - I would estimate at the moment it will take me another month or so.

jnm2 commented 2 years ago

I'm up for trying but also not in a hurry or guaranteed to have time.

YairHalberstadt commented 2 years ago

Well.let me know if/when you want to have a go, and I'll push what I've done so far.