Variance on a method returning ContainerResource or ProjectResource #13078
-
|
I am currently just playing around with the idea to have an extension returning either the project (for env=development) or a deployed version of some (for env=production).
Both share a lot of interfaces like Is there some way using generics to have a method that returns It might also be possible to write a class that wraps it using constrains, but then I again don't know how to call it as I would need to pass it a type that's part of the inheritance chain. The idea is that the references between them, stuff like environment variables or endpoints are still the same, no matter the environment. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
|
I've also run into this and have had the same observation/reflection when setting defaults for my resources automatically. I usually need a resource object with two or more interfaces mentioned. Right now we have to pattern match for ProjectResource, ContainerResource, etc and duplicate code for them. Basically I want |
Beta Was this translation helpful? Give feedback.
-
|
I was able to find a light-weight solution that doesn't crash. Just in case someone else has a similar need. internal interface IProjectOrContainerResource : IResourceWithEnvironment, IResourceWithArgs, IResourceWithEndpoints, IResourceWithWaitSupport, IComputeResource;
internal class ProjectOrContainerResourceBuilder<T>(IResourceBuilder<T> builder) : IResourceBuilder<IProjectOrContainerResource>
where T : IResourceWithEnvironment, IResourceWithArgs, IResourceWithEndpoints, IResourceWithWaitSupport, IComputeResource
{
private IResourceBuilder<T> _builder = builder;
public IResourceBuilder<IProjectOrContainerResource> WithAnnotation<TAnnotation>(
TAnnotation annotation,
ResourceAnnotationMutationBehavior behavior = ResourceAnnotationMutationBehavior.Append) where TAnnotation : IResourceAnnotation
{
_builder = _builder.WithAnnotation(annotation, behavior);
return this;
}
public IDistributedApplicationBuilder ApplicationBuilder => _builder.ApplicationBuilder;
public IProjectOrContainerResource Resource => Unsafe.As<IProjectOrContainerResource>(_builder.Resource);
}This can then be used like Still not sure why directly using Sadly it's not possible to also inherit |
Beta Was this translation helpful? Give feedback.
I was able to find a light-weight solution that doesn't crash. Just in case someone else has a similar need.