Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AddSwaggerExamplesFrom methods should be more discriminating #206

Open
DDtMM opened this issue May 11, 2022 · 0 comments
Open

AddSwaggerExamplesFrom methods should be more discriminating #206

DDtMM opened this issue May 11, 2022 · 0 comments

Comments

@DDtMM
Copy link

DDtMM commented May 11, 2022

I was trying to implement the code below because I thought it would be straight forward to do. Basically I had some means where by for each type I could generate meaningful property values (the implementation details are not important).

The problem is, that no matter how hard I try AddSwaggerExamplesFromAssemblyOf() would try to include the AutoExample class (many instances Like AutoExample<string>, AutoExample<SomethingElse>, etc..). This happens even though the class is private.

Maybe the methodology should be it should ignore private/protected classes, classes that have generic type parameters, or classes with a certain attribute? Or maybe there is an easier way for what I'm trying to do?

public static class AutoExampleExtensions
{
    // please skip me AddSwaggerExamplesFromAssemblyOf!
    private class AutoExample<T> : IExamplesProvider<T>
    {
        public T GetExamples() {  /** **/ }
    }

    public static IServiceCollection AddAutoExamples(this IServiceCollection services, params Type[] types)
    {
        foreach (Type type in types)
        {
            Type exampleType = typeof(AutoExample<>).MakeGenericType(type);
            object example = Activator.CreateInstance(exampleType)!;
            services.AddSingleton(exampleType.GetInterfaces().First(x => typeof(IExamplesProvider<>) == x.GetGenericTypeDefinition()), example);
        }
        return services;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant