I have an ASP.NET backend project that includes several small class library projects as references.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\Background\Publisher\Publisher.csproj" />
<ProjectReference Include="..\src\Common\Common.csproj" />
<ProjectReference Include="..\src\Data\Data.csproj" />
<ProjectReference Include="..\src\Identity\Identity.csproj" />
<ProjectReference Include="..\src\Transaction\Transaction.csproj" />
</ItemGroup>
</Project>
I plan to register all services defined in these class libraries using assembly in the ConfigureServices method:
public static void ConfigureServices(this IServiceCollection services)
{
// TODO: Get all project references as an array to optimize below code.
var serviceTypes = Assembly.GetExecutingAssembly().GetTypes();
var idTypes = Assembly.Load("Identity").GetTypes();
var txTypes = Assembly.Load("Transaction").GetTypes();
serviceTypes = serviceTypes.Concat(idTypes).Concat(txTypes).ToArray()
.Where(t => typeof(IService).IsAssignableFrom(t)
&& !t.IsInterface && !t.IsAbstract)
.ToArray();
foreach (var serviceType in serviceTypes)
{
var interfaceType = serviceType.GetInterfaces()
.FirstOrDefault(i => typeof(IService).IsAssignableFrom(i));
if (interfaceType != null)
{
services.AddScoped(interfaceType, serviceType);
}
}
}
Here are some sample services I am working with.
// Common library
public interface IService
{
}
// Identity library
public interface IUserService : IService
{
}
public class UserService : IUserService
{
}
// Transaction library
public interface ITransactionService : IService
{
}
public class TransactionService : ITransactionService
{
}
Is it possible to retrieve all the referenced library projects as an array within the ConfigureServices method of Startup?
