1

I have the situation where I cannot edit the global.asax yet I need to wire up a ServiceStack service. I'm using PreApplicationStartMethod which works well but where it gets interesting is I need to allow other developers to plugin their own services in to my service.

In case they have their own APIs defined within their assembly, I've created an interface they can implement; my thinking is I can find the assemblies by looking for classes which implements that and pass it to ServiceStack. This also works well.

The issue however is using AppDomain.CurrentDomain.GetAssemblies() which only loads those dlls which are referenced (which won't be the case) so I looked at using BuildManager.GetReferencedAssemblies() instead but I can't do that within PreApplicationStartMethod as it throws an error:

This method cannot be called during the application's pre-start initialization phase.

Does anyone know how I can work around this? Or use Application_Start? I have included my code below in case it helps:

    private static Assembly[] GetServicesFromAssemblies()
    {
        var serviceType = typeof(IUCommerceApiService);
        var assemblies = GetAssemblies();
        return  assemblies
                    .SelectMany(s => s.GetTypes())
                    .Where(serviceType.IsAssignableFrom)
                    .Select(t => t.Assembly)
                    .Distinct()
                    .ToArray();
    }

    // Works until app pool refresh
    private static IEnumerable<Assembly> GetAssemblies()
    {
        return AppDomain.CurrentDomain.GetAssemblies();
    }

    // Throws error when called within PreApplicationStartMethod
    private static IEnumerable<Assembly> GetAssemblies()
    {
        return new ReadOnlyCollection<Assembly>(BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList());
    }
4

0 回答 0