私が行っているように依存関係を動的に解決するのは良いことですか?どこでもコンストラクタインジェクションを使用することをお勧めします。私はそれをやっているやり方の欠点を本当に理解していません。以下のようにコードスニペット..Autofacを使用して依存関係を動的に解決する
Employee.cs
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Department Department { get; set; }
}
IRepository.cs
public interface IRepository<TModel> where TModel : class
{
void Add();
IEnumerable<TModel> GetAll();
IEnumerable<TModel> GetByID();
}
Repository.cs
public class Repository<TModel> : IRepository<TModel> where TModel : class
{
public void Add()
{
throw new NotImplementedException();
}
public IEnumerable<TModel> GetAll()
{
throw new NotImplementedException();
}
public IEnumerable<TModel> GetByID()
{
throw new NotImplementedException();
}
}
EmployeeController.cs Global.asaxの
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
var container = builder.Build(Autofac.Builder.ContainerBuildOptions.None);
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
}
iが5つのリポジトリをしたと言う
public class HomeController : ApiController
{
IComponentContext _container;
public HomeController(IComponentContext container)
{
this._container = container;
}
public Repository<TModel> Using<TModel>() where TModel :class
{
var repository = _container.Resolve(typeof(IRepository<TModel>));
return repository as Repository<TModel>;
}
[HttpGet]
public IEnumerable<Employee> GetEmployees()
{
return Using<Employee>().GetAll();
}
}
、コンストラクタ・インジェクションは、私が作る要求のためのすべての5つの依存関係を解決します。私はそれぞれのリクエストごとに5つのリポジトリを使用しないかもしれません。だから私はそれをやっているような型を渡すことによって依存関係を動的に解決すると思ったUsing<TModel>()
。どんな提案も高く評価されます。ありがとうございました...!!
基本的には、コンテナを直接使用してアンチパターンとみなすサービスロケータパターンを使用しています。詳細はこちら http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ 私は個人的には、必要なリポジトリだけを注入する複数のコントローラに分割します。だからEmployeeControllerなど。 –
@Praveenに直接 'container'を使わないでください。 'IDependencyResolver.GetService'でIoCコンテナを使って登録された型を解決するだけで十分です。 –