问题
Currently, I have below 4 projects in my solution file :
- API (Web API)
- Web (MVC)
- Admin (MVC)
- 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