Skip to content

AddSwaggerExamplesFrom methods should be more discriminating #206

Open
@DDtMM

Description

@DDtMM

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;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions