Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

c# - Inject existing object into asp.net web api 2 controller

I want to send data from an existing project over HTTP. To do that I decided to use OWIN to self-host a web server from that particular project (I followed this, not sure this is the best way though). This existing project has some objects that need to serve as a model for the controller's web API. My problem is that I don't know how to pass an existing object to a controller. Dependency injection seems to only allow me to create new objects, furthermore the object is only available at the point where I start the web app. Here is the code

private void Initialize()
{
    // TODO: this object needs to somehow end up in the controllers.
    CustomObject object = base.object;
    _webApp = WebApp.Start(baseAddress, Startup);
}

private void Startup(IAppBuilder appBuilder)
{
    // Configure Web API for self-host.
    HttpConfiguration config = new HttpConfiguration();
    config.Routes.MapHttpRoute(
        name: "REST API",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    config.Services.Replace(typeof(IAssembliesResolver), new MyAssembliesResolver());

    appBuilder.UseWebApi(config);
}

public class ValuesController : ApiController
{
    // TODO: so this needs to be filled in with the object from the Initialize() method above.
    private CustomObject _customObject; 

    // GET api/values
    public IEnumerable<string> GetAll()
    {
        // I want to use this customObject to send information about the project that is actually hosting the web api.
        // return _customObject.Data;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...