Common code for dependency injection for web api, admin panel and mvc controller

此生再无相见时 提交于 2019-12-24 10:08:52

问题


Currently, I have below 4 projects in my solution file :

  1. API (Web API)
  2. Web (MVC)
  3. Admin (MVC)
  4. Service Layer (C# Library)

The service layer is being used by all the 3 web projects. The service is injected using Autofac container.

The services are registered in each of the web projects during startup which is causing duplication of the code. Is there a simpler way where I can register all the dependencies in one place so that it can be reused by all the projects?

Any help is highly appreciated.


回答1:


Your service layer should be registering instances of interfaces (programming against an interface). For example:

// Services.DLL
public interface IMyInterface
{
  void DoFoo();
}

internal class MyClass : IMyInterface
{
  public void DoFoo()
  {
  }
}

Then you can simply use Aufofac's Scanning For Modules:

// Services.Dll
public class ServicesRegistrion : Module
{
  protected override void Load(ContainerBuilder builder)
  {
    builder.Register<MyClass>()
      .As<IMyInterface>()
      .InstancePerLifetimeScope();
  }
}

Then in each project:

var assemblies = BuildManager
  .GetReferencedAssemblies()
  .Cast<Assembly>();

foreach(var assembly in assemblies)
{
  builder.RegisterAssemblyModules(assembly);
}



回答2:


One more approach you can try

  • Add a common file like AutofacBootstrap, expose a static method which excepts Autofac Container, this method should register all your common classes. You can have this file in a separate common project.

  • Include that class as a link to other projects. For this Right-click the project, select Add > Existing Item, and in the dialog drop down the Add button and select Add As Link.

    Now you have a common file which have a link to all the projects.

  • Next is, in startup of individual project, call the common method by passing the container. In addition bootstrap your local dependencies.

I hope this helps.



来源:https://stackoverflow.com/questions/48558134/common-code-for-dependency-injection-for-web-api-admin-panel-and-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!