Blazor Server Template - Scrutor

2022. 5. 10. 00:00ASPNET/BlazorServerTemplate

반응형

Helper 폴더 추가 --> AssemblyHelper.cs 추가

using System.Diagnostics;
using System.Reflection;
using System.Runtime.Loader;

namespace BlazorWebApp.Helper;

public class AssemblyHelper
{
    public static List<Assembly> GetAllAssemblies(SearchOption searchOption = SearchOption.TopDirectoryOnly)
    {
        List<Assembly> assemblies = new List<Assembly>();

        foreach (string assemblyPath in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll", searchOption))
        {
            try
            {
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);

                if (assemblies.Find(a => a == assembly) != null)
                    continue;

                assemblies.Add(assembly);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
        return assemblies;
    }
}

Scrutor 추가
 
개발자 프롬프트에서 프로젝트 폴더로 이동 
(현재 .sln 파일이 있는 폴더라면 .csproj 파일이 있는 폴더로 이동)
 
아래 명령 실행
 
dotnet add package Scrutor
 
Injectables 폴더 추가
Injectable.cs 추가

namespace BlazorWebApp.Injectables;
public interface IInjectableService { }
public interface ITransientService : IInjectableService { }
public interface IScopedService : IInjectableService { }
public interface ISingletonService : IInjectableService { }

Program.cs 에 다음 코드 추가

using BlazorWebApp.Helper;
using BlazorWebApp.Injectables;
...
...
builder.Services.Scan(scan => scan
                            .FromAssemblies(AssemblyHelper.GetAllAssemblies())
                            .AddClasses(classes => classes.AssignableTo<ITransientService>())
                            .AsImplementedInterfaces()
                            .WithTransientLifetime()
                            .AddClasses(classes => classes.AssignableTo<IScopedService>())
                            .AsImplementedInterfaces()
                            .WithScopedLifetime()
                            .AddClasses(classes => classes.AssignableTo<ISingletonService>())
                            .AsImplementedInterfaces()
                            .WithSingletonLifetime()
                            );

FetchData 를 Injectables.cs 를 이용하여 수정해보기

 

Data/WeatherForecastService.cs 수정

using BlazorWebApp.Injectables;

namespace BlazorWebApp.Data
{
    public interface IWeatherForecastService : ISingletonService
    {
        Task<WeatherForecast[]> GetForecastAsync(DateTime startDate);
    }

    public class WeatherForecastService: IWeatherForecastService
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
        {
            return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = startDate.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            }).ToArray());
        }
    }
}

Pages/FetchData.razor 수정

...
@inject IWeatherForecastService ForecastService // WeatherForecastServic -->IWeatherForecastService
...

 

Program.cs  수정

// builder.Services.AddSingleton<WeatherForecastService>(); //  comment 처리 또는 삭제

 

 

 

관련영상

https://youtu.be/bPxzHrQ5n7I

 

반응형